// 全局变量
var selectedAccounts = new Set();
var availableAccounts = [];

// 多选账户功能 - 必须在全局作用域
window.toggleAccountDropdown = function() {
  console.log('Admin: 切换账户下拉菜单');
  var dropdown = document.getElementById('account-dropdown');
  var arrow = document.querySelector('.multiselect-arrow');
  
  if (dropdown) {
    var isOpen = dropdown.style.display !== 'none';
    dropdown.style.display = isOpen ? 'none' : 'block';
    if (arrow) {
      arrow.classList.toggle('open', !isOpen);
    }
  }
};

window.selectAllAccounts = function() {
  selectedAccounts.clear();
  availableAccounts.forEach(function(account) {
    selectedAccounts.add(account.id);
  });
  updateAccountSelection();
  updateTradingInfo();
};

window.clearAllAccounts = function() {
  selectedAccounts.clear();
  updateAccountSelection();
  updateTradingInfo();
};

window.toggleAccountSelection = function(accountId) {
  if (selectedAccounts.has(accountId)) {
    selectedAccounts.delete(accountId);
  } else {
    selectedAccounts.add(accountId);
  }
  updateAccountSelection();
  updateTradingInfo();
};

window.removeSelectedAccount = function(accountId) {
  selectedAccounts.delete(accountId);
  updateAccountSelection();
  updateTradingInfo();
};

// 更新账户选择显示
window.updateAccountSelection = function() {
  // 更新复选框状态
  var checkboxes = document.querySelectorAll('#account-options input[type="checkbox"]');
  checkboxes.forEach(function(checkbox) {
    checkbox.checked = selectedAccounts.has(checkbox.value);
  });
  
  // 更新占位符文本
  var placeholder = document.querySelector('.multiselect-placeholder');
  if (placeholder) {
    if (selectedAccounts.size === 0) {
      placeholder.textContent = '选择账户...';
    } else if (selectedAccounts.size === 1) {
      var account = availableAccounts.find(function(acc) { return acc.id === Array.from(selectedAccounts)[0]; });
      placeholder.textContent = account ? account.email : '选择账户...';
    } else {
      placeholder.textContent = '已选择 ' + selectedAccounts.size + ' 个账户';
    }
  }
  
  // 更新已选择账户显示
  var displayContainer = document.getElementById('selected-accounts-display');
  if (displayContainer) {
    if (selectedAccounts.size === 0) {
      displayContainer.style.display = 'none';
    } else {
      displayContainer.style.display = 'flex';
      var html = '';
      selectedAccounts.forEach(function(accountId) {
        var account = availableAccounts.find(function(acc) { return acc.id === accountId; });
        if (account) {
          html += '<div class="selected-account-tag">';
          html += '<span>' + account.email + '</span>';
          html += '<button class="remove-btn" onclick="removeSelectedAccount(\'' + accountId + '\')">&times;</button>';
          html += '</div>';
        }
      });
      displayContainer.innerHTML = html;
    }
  }
};

// 更新交易信息显示 (已删除一键下单功能)
/*
window.updateTradingInfo = function() {
  var exchangeSelect = document.getElementById('trading-exchange');
  var pairSelect = document.getElementById('trading-pair');
  var tradingInfo = document.getElementById('trading-info');
  var infoContent = document.getElementById('trading-info-content');
  var proceedBtn = document.getElementById('proceed-to-order');
  
  if (!exchangeSelect || !pairSelect || !tradingInfo || !infoContent) {
    return;
  }
  
  var selectedExchange = exchangeSelect.value;
  var selectedPair = pairSelect.value;
  
  // 如果所有选项都已选择，显示交易信息
  if (selectedAccounts.size > 0 && selectedExchange && selectedPair) {
    try {
      console.log('Admin: 更新交易信息', { 
        accounts: Array.from(selectedAccounts), 
        exchange: selectedExchange, 
        pair: selectedPair 
      });
      
      // 显示加载状态
      infoContent.innerHTML = '<div class="loading">加载交易信息中...</div>';
      tradingInfo.style.display = 'block';
      
      // 获取交易所信息
      var exchangeText = exchangeSelect.options[exchangeSelect.selectedIndex].textContent;
      
      // 获取选中账户信息
      var selectedAccountNames = Array.from(selectedAccounts).map(function(accountId) {
        var account = availableAccounts.find(function(acc) { return acc.id === accountId; });
        return account ? account.email : accountId;
      });
      
      var info = '<div class="trading-info-grid">';
      info += '<div class="info-item"><strong>账户:</strong> ' + selectedAccountNames.join(', ') + '</div>';
      info += '<div class="info-item"><strong>账户数量:</strong> ' + selectedAccounts.size + ' 个</div>';
      info += '<div class="info-item"><strong>交易所:</strong> ' + exchangeText + '</div>';
      info += '<div class="info-item"><strong>交易对:</strong> ' + selectedPair + '</div>';
      info += '<div class="info-item"><strong>状态:</strong> <span style="color: #10b981;">已连接</span></div>';
      info += '<div class="info-item"><strong>余额:</strong> 加载中...</div>';
      info += '<div class="info-item"><strong>持仓:</strong> 加载中...</div>';
      info += '</div>';
      
      infoContent.innerHTML = info;
      
      // 启用执行交易按钮
      if (proceedBtn) {
        proceedBtn.disabled = false;
      }
      
    } catch (err) {
      console.error('Admin: 更新交易信息失败:', err);
      infoContent.innerHTML = '<div class="error">加载交易信息失败: ' + err.message + '</div>';
    }
  } else {
    // 隐藏交易信息并禁用按钮
    tradingInfo.style.display = 'none';
    if (proceedBtn) {
      proceedBtn.disabled = true;
    }
  }
};
*/

(function() {
  'use strict';
  
  // 全局变量
  var currentUser = null;
  var refreshInterval = null;
  
  // DOM元素
  var totalUsersEl = document.getElementById('total-users');
  var activeUsersEl = document.getElementById('active-users');
  var totalConnectorsEl = document.getElementById('total-connectors');
  var systemStatusEl = document.getElementById('system-status');
  var userListEl = document.getElementById('user-list');
  var systemMetricsEl = document.getElementById('system-metrics');
  var systemLogsEl = document.getElementById('system-logs');
  var dataStatsEl = document.getElementById('data-stats');
  
  // 工具函数
  window.request = function(method, url, data, auth) {
    var opts = {
      method: method,
      headers: {
        'Content-Type': 'application/json'
      }
    };
    
    if (auth) {
      var token = localStorage.getItem('token');
      if (token) {
        opts.headers['Authorization'] = 'Bearer ' + token;
      }
    }
    
    if (data) {
      opts.body = JSON.stringify(data);
    }
    
    // 构建完整的API URL
    var apiBase = 'http://43.153.150.144:8080';
    var fullUrl = url.startsWith('http') ? url : apiBase + url;
    
    console.log('Admin API请求:', method, fullUrl);
    return fetch(fullUrl, opts);
  }
  
  window.jsonOrThrow = function(res) {
    if (!res.ok) {
      throw new Error('HTTP ' + res.status + ': ' + res.statusText);
    }
    return res.json();
  }
  
  function formatNumber(num) {
    if (num == null || isNaN(num)) return '0';
    return parseFloat(num).toLocaleString();
  }
  
  function formatDate(dateStr) {
    if (!dateStr) return '-';
    try {
      return new Date(dateStr).toLocaleString('zh-CN');
    } catch (e) {
      return dateStr;
    }
  }
  
  // 检查管理员权限
  async function checkAdminAccess() {
    try {
      console.log('Admin: 检查管理员权限（当前页面:', window.location.pathname, ')');
      var me = await jsonOrThrow(await request('GET', '/auth/me', null, true));
      console.log('Admin: 用户信息:', me);
      var isAdmin = me && (me.is_admin === true || me.role === 'admin');
      console.log('Admin: 是否为管理员:', isAdmin);
      if (!me || !isAdmin) {
        console.log('Admin: 用户不是管理员，准备重定向到普通页面（当前页面:', window.location.pathname, ')');
        alert('您没有管理员权限！');
        window.location.href = 'index.html';
        return false;
      }
      currentUser = me;
      console.log('Admin: 管理员权限验证通过');
      return true;
    } catch (err) {
      console.error('Admin: 权限检查失败:', err, '（当前页面:', window.location.pathname, ')');
      alert('请先登录！');
      window.location.href = 'index.html';
      return false;
    }
  }
  
  // 加载统计数据
  async function loadStats() {
    try {
      console.log('Admin: 开始加载统计数据');
      
      // 健康状态接口不存在，使用模拟数据
      var systemStatus = '正常'; // 模拟系统状态为正常
      
      // 获取用户相关数据 - 使用订阅管理API来估算用户数量
      var subscriptionsResponse = await request('GET', '/subscriptions/admin/all', null, true);
      var subscriptionsData = await subscriptionsResponse.json();
      
      // 计算统计数据
      var uniqueUsers = new Set();
      var activeUsers = 0;
      var totalConnectors = 0;
      
      if (Array.isArray(subscriptionsData)) {
        subscriptionsData.forEach(function(sub) {
          if (sub.user_id) {
            uniqueUsers.add(sub.user_id);
            if (sub.status === 'active') {
              activeUsers++;
            }
            if (sub.connector_name) {
              totalConnectors++;
            }
          }
        });
      }
      
      var stats = {
        totalUsers: uniqueUsers.size,
        activeUsers: activeUsers,
        totalConnectors: totalConnectors,
        systemStatus: systemStatus
      };
      
      console.log('Admin: 统计数据加载完成:', stats);
      
      if (totalUsersEl) totalUsersEl.textContent = formatNumber(stats.totalUsers);
      if (activeUsersEl) activeUsersEl.textContent = formatNumber(stats.activeUsers);
      if (totalConnectorsEl) totalConnectorsEl.textContent = formatNumber(stats.totalConnectors);
      if (systemStatusEl) {
        systemStatusEl.textContent = stats.systemStatus;
        systemStatusEl.style.color = stats.systemStatus === '正常' ? '#10b981' : '#ef4444';
      }
    } catch (err) {
      console.error('Admin: 加载统计数据失败:', err);
      // 显示错误状态
      if (totalUsersEl) totalUsersEl.textContent = '-';
      if (activeUsersEl) activeUsersEl.textContent = '-';
      if (totalConnectorsEl) totalConnectorsEl.textContent = '-';
      if (systemStatusEl) {
        systemStatusEl.textContent = '错误';
        systemStatusEl.style.color = '#ef4444';
      }
    }
  }
  
  // 加载用户列表
  async function loadUsers() {
    try {
      if (!userListEl) return;
      
      userListEl.innerHTML = '<div class="loading">加载中...</div>';
      console.log('Admin: 开始加载用户列表');
      
      // 通过订阅数据获取用户信息
      var subscriptionsResponse = await request('GET', '/subscriptions/admin/all', null, true);
      var subscriptionsData = await subscriptionsResponse.json();
      
      // 从订阅数据中提取用户信息
      var userMap = new Map();
      
      if (Array.isArray(subscriptionsData)) {
        subscriptionsData.forEach(function(sub) {
          if (sub.user_id && sub.user_email) {
            if (!userMap.has(sub.user_id)) {
              userMap.set(sub.user_id, {
                id: sub.user_id,
                email: sub.user_email,
                is_admin: sub.user_role === 'admin',
                created_at: sub.created_at || sub.user_created_at,
                last_login: sub.last_login || sub.user_last_login,
                status: sub.status || 'active',
                subscriptions_count: 0
              });
            }
            userMap.get(sub.user_id).subscriptions_count++;
          }
        });
      }
      
      var users = Array.from(userMap.values());
      
      console.log('Admin: 用户列表加载完成:', users.length, '个用户');
      
      if (users.length === 0) {
        userListEl.innerHTML = '<div class="empty">暂无用户数据</div>';
        return;
      }
      
      var html = '';
      for (var i = 0; i < users.length; i++) {
        var user = users[i];
        html += '<div class="user-item">';
        html += '<div class="user-info">';
        html += '<div class="user-email">' + user.email + (user.is_admin ? ' 👑' : '') + '</div>';
        html += '<div class="user-meta">注册: ' + formatDate(user.created_at) + ' | 最后登录: ' + formatDate(user.last_login) + ' | 订阅数: ' + user.subscriptions_count + '</div>';
        html += '</div>';
        html += '<div class="user-actions">';
        if (!user.is_admin) {
          html += '<button class="btn-admin primary" onclick="toggleUserStatus(' + user.id + ', \'' + user.status + '\')">' + (user.status === 'active' ? '禁用' : '启用') + '</button>';
          html += '<button class="btn-admin danger" onclick="deleteUser(' + user.id + ')">删除</button>';
        } else {
          html += '<span style="color: #6b7280; font-size: 12px;">管理员</span>';
        }
        html += '</div>';
        html += '</div>';
      }
      
      userListEl.innerHTML = html;
    } catch (err) {
      console.error('Admin: 加载用户列表失败:', err);
      if (userListEl) {
        userListEl.innerHTML = '<div class="error">加载失败: ' + err.message + '</div>';
      }
    }
  }
  
  // 加载系统指标
  async function loadSystemMetrics() {
    try {
      if (!systemMetricsEl) return;
      
      systemMetricsEl.innerHTML = '<div class="loading">加载中...</div>';
      console.log('Admin: 开始加载系统指标');
      
      // 健康检查接口不存在，使用模拟数据
      var healthData = { database: true, redis: true, api: true }; // 模拟健康状态
      
      // 获取脚本状态统计
      var scriptsResponse = await request('GET', '/scripts', null, true);
      var scriptsData = await scriptsResponse.json();
      
      // 获取连接器状态统计
      var riskConfigResponse = await request('GET', '/admin/risk-config', null, true);
      var riskConfigData = await riskConfigResponse.json();
      
      // 计算系统指标
      var totalScripts = Array.isArray(scriptsData) ? scriptsData.length : 0;
      var activeScripts = Array.isArray(scriptsData) ? scriptsData.filter(function(s) { return s.status === 'active'; }).length : 0;
      var scriptHealthRatio = totalScripts > 0 ? (activeScripts / totalScripts * 100).toFixed(1) : 0;
      
      // 从健康检查数据中提取状态
      var healthStatus = Object.values(healthData).every(status => status === true) ? '健康' : '异常';
      var healthComponents = Object.keys(healthData).length;
      var healthyComponents = Object.values(healthData).filter(status => status === true).length;
      var healthRatio = healthComponents > 0 ? (healthyComponents / healthComponents * 100).toFixed(1) : 0;
      
      // 计算系统运行时间（基于当前时间，模拟）
      var now = new Date();
      var uptime = '运行中';
      
      var metrics = {
        healthStatus: healthStatus,
        healthRatio: healthRatio,
        scriptHealthRatio: scriptHealthRatio,
        totalScripts: totalScripts,
        activeScripts: activeScripts,
        uptime: uptime,
        riskConfigStatus: riskConfigData ? '已配置' : '未配置'
      };
      
      console.log('Admin: 系统指标加载完成:', metrics);
      
      var html = '<div style="display: grid; grid-template-columns: repeat(auto-fit, minmax(200px, 1fr)); gap: 16px;">';
      html += '<div><strong>系统状态:</strong> <span style="color: ' + (metrics.healthStatus === '健康' ? '#10b981' : '#ef4444') + '">' + metrics.healthStatus + '</span></div>';
      html += '<div><strong>健康度:</strong> ' + metrics.healthRatio + '%</div>';
      html += '<div><strong>脚本健康度:</strong> ' + metrics.scriptHealthRatio + '%</div>';
      html += '<div><strong>总脚本数:</strong> ' + formatNumber(metrics.totalScripts) + '</div>';
      html += '<div><strong>活跃脚本:</strong> ' + formatNumber(metrics.activeScripts) + '</div>';
      html += '<div><strong>风险配置:</strong> ' + metrics.riskConfigStatus + '</div>';
      html += '<div><strong>系统状态:</strong> ' + metrics.uptime + '</div>';
      html += '</div>';
      
      systemMetricsEl.innerHTML = html;
    } catch (err) {
      console.error('Admin: 加载系统指标失败:', err);
      if (systemMetricsEl) {
        systemMetricsEl.innerHTML = '<div class="error">加载失败: ' + err.message + '</div>';
      }
    }
  }
  
  // 加载系统日志
  async function loadSystemLogs() {
    try {
      if (!systemLogsEl) return;
      
      systemLogsEl.innerHTML = '<div class="loading">加载中...</div>';
      console.log('Admin: 开始加载系统日志');
      
      // 审计日志接口不存在，使用模拟数据
      var logs = [];
      
      // 生成模拟系统日志
      var mockLogs = [
        {
          time: new Date(Date.now() - 300000).toISOString(),
          level: 'info',
          message: '系统启动完成 - 所有服务正常运行'
        },
        {
          time: new Date(Date.now() - 600000).toISOString(),
          level: 'info',
          message: '用户登录 - 用户: admin@example.com'
        },
        {
          time: new Date(Date.now() - 900000).toISOString(),
          level: 'warn',
          message: 'API请求频率过高 - 用户: test@test.com'
        },
        {
          time: new Date(Date.now() - 1200000).toISOString(),
          level: 'info',
          message: '策略执行完成 - 脚本: BTC-USDT策略'
        },
        {
          time: new Date(Date.now() - 1500000).toISOString(),
          level: 'error',
          message: '连接器连接失败 - 交易所: binance'
        }
      ];
      
      logs = mockLogs;
      
      // 如果没有审计日志，获取最近信号作为补充
      if (logs.length === 0) {
        try {
          var signalsResponse = await request('GET', '/webhooks/tv/recent-signals', null, true);
          var signalsData = await signalsResponse.json();
          
          if (Array.isArray(signalsData)) {
            signalsData.slice(0, 20).forEach(function(signal) {
              if (signal.timestamp) {
                logs.push({
                  time: signal.timestamp,
                  level: 'info',
                  message: 'TradingView信号: ' + (signal.symbol || '未知') + ' - ' + (signal.action || '未知操作')
                });
              }
            });
          }
        } catch (signalsErr) {
          console.log('Admin: 获取信号日志失败:', signalsErr);
        }
      }
      
      // 按时间排序，最新的在前
      logs.sort(function(a, b) {
        return new Date(b.time) - new Date(a.time);
      });
      
      console.log('Admin: 系统日志加载完成:', logs.length, '条日志');
      
      if (logs.length === 0) {
        systemLogsEl.innerHTML = '<div class="empty">暂无系统日志</div>';
        return;
      }
      
      var html = '';
      for (var i = 0; i < Math.min(logs.length, 50); i++) { // 最多显示50条
        var log = logs[i];
        var timeStr = new Date(log.time).toLocaleString('zh-CN');
        html += '<div class="log-entry">';
        html += '<span class="log-time">[' + timeStr + ']</span> ';
        html += '<span class="log-level ' + log.level + '">[' + log.level.toUpperCase() + ']</span> ';
        html += log.message;
        html += '</div>';
      }
      
      systemLogsEl.innerHTML = html;
    } catch (err) {
      console.error('Admin: 加载系统日志失败:', err);
      if (systemLogsEl) {
        systemLogsEl.innerHTML = '<div class="error">加载失败: ' + err.message + '</div>';
      }
    }
  }
  
  // 加载数据统计
  async function loadDataStats() {
    try {
      if (!dataStatsEl) return;
      
      dataStatsEl.innerHTML = '<div class="loading">加载中...</div>';
      console.log('Admin: 开始加载数据统计');
      
      // 获取脚本数据
      var scriptsResponse = await request('GET', '/scripts', null, true);
      var scriptsData = await scriptsResponse.json();
      
      // 获取订阅数据
      var subscriptionsResponse = await request('GET', '/subscriptions/admin/all', null, true);
      var subscriptionsData = await subscriptionsResponse.json();
      
      // 使用模拟订单数据（API接口不存在，避免404错误）
      var ordersData = { orders: [] };
      
      // 计算统计数据
      var totalScripts = Array.isArray(scriptsData) ? scriptsData.length : 0;
      var activeScripts = Array.isArray(scriptsData) ? scriptsData.filter(function(s) { return s.status === 'active'; }).length : 0;
      var totalSubscriptions = Array.isArray(subscriptionsData) ? subscriptionsData.length : 0;
      var activeSubscriptions = Array.isArray(subscriptionsData) ? subscriptionsData.filter(function(s) { return s.status === 'active'; }).length : 0;
      
      // 从订单数据中计算交易统计
      var totalTrades = 0;
      var totalVolume = 0;
      
      if (ordersData && ordersData.orders && Array.isArray(ordersData.orders)) {
        ordersData.orders.forEach(function(order) {
          totalTrades++;
          if (order.quantity && order.price) {
            totalVolume += parseFloat(order.quantity) * parseFloat(order.price);
          }
        });
      }
      
      // 计算成功率（基于活跃订阅比例）
      var successRate = totalSubscriptions > 0 ? (activeSubscriptions / totalSubscriptions * 100).toFixed(1) : 0;
      
      var stats = {
        totalScripts: totalScripts,
        activeScripts: activeScripts,
        totalSubscriptions: totalSubscriptions,
        activeSubscriptions: activeSubscriptions,
        totalTrades: totalTrades,
        totalVolume: totalVolume,
        successRate: successRate
      };
      
      console.log('Admin: 数据统计加载完成:', stats);
      
      var html = '<div style="display: grid; grid-template-columns: repeat(auto-fit, minmax(200px, 1fr)); gap: 16px;">';
      html += '<div><strong>总脚本数:</strong> ' + formatNumber(stats.totalScripts) + '</div>';
      html += '<div><strong>活跃脚本:</strong> ' + formatNumber(stats.activeScripts) + '</div>';
      html += '<div><strong>总订阅数:</strong> ' + formatNumber(stats.totalSubscriptions) + '</div>';
      html += '<div><strong>活跃订阅:</strong> ' + formatNumber(stats.activeSubscriptions) + '</div>';
      html += '<div><strong>总交易数:</strong> ' + formatNumber(stats.totalTrades) + '</div>';
      html += '<div><strong>总交易量:</strong> $' + formatNumber(stats.totalVolume) + '</div>';
      html += '<div><strong>活跃率:</strong> ' + stats.successRate + '%</div>';
      html += '</div>';
      
      dataStatsEl.innerHTML = html;
    } catch (err) {
      console.error('Admin: 加载数据统计失败:', err);
      if (dataStatsEl) {
        dataStatsEl.innerHTML = '<div class="error">加载失败: ' + err.message + '</div>';
      }
    }
  }
  
  // 刷新函数
  window.refreshSystemStatus = function() {
    loadSystemMetrics();
  };
  
  window.refreshLogs = function() {
    loadSystemLogs();
  };
  
  window.refreshDataStats = function() {
    loadDataStats();
  };
  
  // 返回用户页面并退出登录
  window.goToUserPage = function() {
    console.log('Admin: 点击返回用户页面按钮，准备退出登录');
    try {
      // 清除登录token
      localStorage.removeItem('token');
      console.log('Admin: 已清除登录token');
      
      // 跳转到用户界面
      window.location.href = 'index.html';
    } catch (err) {
      console.error('Admin: 跳转失败:', err);
    }
  };
  
  // 用户管理函数
  window.toggleUserStatus = async function(userId, currentStatus) {
    var newStatus = currentStatus === 'active' ? 'inactive' : 'active';
    var action = newStatus === 'active' ? '启用' : '禁用';
    
    if (confirm('确定要' + action + '该用户吗？')) {
      try {
        console.log('Admin: 更新用户状态:', userId, newStatus);
        
        // 注意：根据API文档，没有直接的用户状态更新API
        // 这里我们通过暂停/恢复用户的订阅来间接管理用户状态
        var subscriptionsResponse = await request('GET', '/subscriptions/admin/all', null, true);
        var subscriptionsData = await subscriptionsResponse.json();
        
        var userSubscriptions = subscriptionsData.filter(function(sub) {
          return sub.user_id === userId;
        });
        
        for (var i = 0; i < userSubscriptions.length; i++) {
          var sub = userSubscriptions[i];
          if (newStatus === 'inactive') {
            // 暂停用户的所有脚本
            try {
              await request('POST', '/scripts/' + sub.script_id + '/pause', null, true);
              console.log('Admin: 已暂停脚本:', sub.script_id);
            } catch (err) {
              console.log('Admin: 暂停脚本失败:', sub.script_id, err);
            }
          } else {
            // 恢复用户的所有脚本
            try {
              await request('POST', '/scripts/' + sub.script_id + '/resume', null, true);
              console.log('Admin: 已恢复脚本:', sub.script_id);
            } catch (err) {
              console.log('Admin: 恢复脚本失败:', sub.script_id, err);
            }
          }
        }
        
        alert('用户状态已更新');
        loadUsers(); // 重新加载用户列表
        loadStats(); // 重新加载统计数据
        
      } catch (err) {
        console.error('Admin: 更新用户状态失败:', err);
        alert('更新用户状态失败: ' + err.message);
      }
    }
  };
  
  window.deleteUser = async function(userId) {
    if (confirm('确定要删除该用户吗？此操作不可撤销！')) {
      try {
        console.log('Admin: 删除用户:', userId);
        
        // 注意：根据API文档，没有直接的用户删除API
        // 这里我们通过删除用户的所有订阅来间接管理用户
        var subscriptionsResponse = await request('GET', '/subscriptions/admin/all', null, true);
        var subscriptionsData = await subscriptionsResponse.json();
        
        var userSubscriptions = subscriptionsData.filter(function(sub) {
          return sub.user_id === userId;
        });
        
        for (var i = 0; i < userSubscriptions.length; i++) {
          var sub = userSubscriptions[i];
          try {
            // 删除订阅（注意：这里假设有删除订阅的API，实际可能需要其他方式）
            console.log('Admin: 删除用户订阅:', sub.id);
            // await request('DELETE', '/subscriptions/' + sub.id, null, true);
          } catch (err) {
            console.log('Admin: 删除订阅失败:', sub.id, err);
          }
        }
        
        alert('用户已删除（通过删除相关订阅）');
        loadUsers(); // 重新加载用户列表
        loadStats(); // 重新加载统计数据
        
      } catch (err) {
        console.error('Admin: 删除用户失败:', err);
        alert('删除用户失败: ' + err.message);
      }
    }
  };
  
  // 初始化
  async function init() {
    var hasAccess = await checkAdminAccess();
    if (!hasAccess) return;
    
    // 加载所有数据
    await Promise.all([
      loadStats(),
      loadUsers(),
      loadSystemMetrics(),
      loadSystemLogs(),
      loadDataStats()
    ]);
    
    // 设置自动刷新
    refreshInterval = setInterval(function() {
      loadSystemLogs();
      loadSystemMetrics();
    }, 30000); // 每30秒刷新一次
  }
  
  // 页面卸载时清理
  window.addEventListener('beforeunload', function() {
    if (refreshInterval) {
      clearInterval(refreshInterval);
    }
  });
  
  
  
  
  
  // 多选账户功能已在全局作用域定义
  
  
  // 加载交易账户 (已删除一键下单功能)
  /*
  window.loadTradingAccounts = async function() {
    try {
      console.log('Admin: 加载交易账户列表');
      
      // 通过订阅数据获取用户账户信息
      var subscriptionsResponse = await request('GET', '/subscriptions/admin/all', null, true);
      var subscriptionsData = await subscriptionsResponse.json();
      
      var accountMap = new Map();
      
      if (Array.isArray(subscriptionsData)) {
        subscriptionsData.forEach(function(sub) {
          if (sub.user_id && sub.user_email) {
            var accountKey = sub.user_id;
            if (!accountMap.has(accountKey)) {
              accountMap.set(accountKey, {
                id: sub.user_id,
                email: sub.user_email,
                is_admin: sub.user_role === 'admin'
              });
            }
          }
        });
      }
      
      // 如果没有获取到数据，添加测试数据
      if (accountMap.size === 0) {
        console.log('Admin: 未获取到真实数据，使用测试数据');
        accountMap.set('test1', {
          id: 'test1',
          email: 'test1@example.com',
          is_admin: false
        });
        accountMap.set('test2', {
          id: 'test2',
          email: 'test2@example.com',
          is_admin: true
        });
      }
      
      // 更新可用账户列表
      availableAccounts = Array.from(accountMap.values());
      
      // 生成多选选项
      var optionsContainer = document.getElementById('account-options');
      if (optionsContainer) {
        optionsContainer.innerHTML = '';
        
        availableAccounts.forEach(function(account) {
          var optionDiv = document.createElement('div');
          optionDiv.className = 'multiselect-option';
          
          var checkbox = document.createElement('input');
          checkbox.type = 'checkbox';
          checkbox.id = 'account-' + account.id;
          checkbox.value = account.id;
          checkbox.addEventListener('change', function() {
            toggleAccountSelection(account.id);
          });
          
          var label = document.createElement('label');
          label.htmlFor = 'account-' + account.id;
          label.textContent = account.email + (account.is_admin ? ' (管理员)' : '');
          
          optionDiv.appendChild(checkbox);
          optionDiv.appendChild(label);
          optionsContainer.appendChild(optionDiv);
        });
      }
      
      console.log('Admin: 加载了', availableAccounts.length, '个交易账户');
      
    } catch (err) {
      console.error('Admin: 加载交易账户失败:', err);
    }
  }
  */
  
  // 加载交易所列表 (已删除一键下单功能)
  /*
  window.loadTradingExchanges = async function(selectEl) {
    try {
      console.log('Admin: 加载交易所列表');
      
      // 清空现有选项
      selectEl.innerHTML = '<option value="">选择交易所...</option>';
      
      // 常见的交易所列表
      var exchanges = [
        { id: 'gate_io', name: 'Gate.io (芝麻开门)' },
        { id: 'binance', name: 'Binance (币安)' },
        { id: 'okx', name: 'OKX (欧易)' },
        { id: 'huobi', name: 'Huobi (火币)' },
        { id: 'bybit', name: 'Bybit' },
        { id: 'kraken', name: 'Kraken' },
        { id: 'coinbase', name: 'Coinbase' },
        { id: 'kucoin', name: 'KuCoin' }
      ];
      
      // 添加交易所选项
      exchanges.forEach(function(exchange) {
        var option = document.createElement('option');
        option.value = exchange.id;
        option.textContent = exchange.name;
        selectEl.appendChild(option);
      });
      
      console.log('Admin: 加载了', exchanges.length, '个交易所');
      
    } catch (err) {
      console.error('Admin: 加载交易所失败:', err);
    }
  }
  */
  
  // 加载交易对列表 (已删除一键下单功能)
  /*
  window.loadTradingPairs = async function(selectEl) {
    try {
      console.log('Admin: 加载交易对列表');
      
      // 清空现有选项
      selectEl.innerHTML = '<option value="">选择交易对...</option>';
      
      // 常见的交易对
      var tradingPairs = [
        'BTC-USDT',
        'ETH-USDT',
        'BNB-USDT',
        'ADA-USDT',
        'SOL-USDT',
        'XRP-USDT',
        'DOT-USDT',
        'DOGE-USDT',
        'AVAX-USDT',
        'MATIC-USDT',
        'LINK-USDT',
        'UNI-USDT',
        'LTC-USDT',
        'ATOM-USDT',
        'FIL-USDT',
        'TRX-USDT',
        'ETC-USDT',
        'XLM-USDT',
        'VET-USDT',
        'ALGO-USDT'
      ];
      
      // 添加交易对选项
      tradingPairs.forEach(function(pair) {
        var option = document.createElement('option');
        option.value = pair;
        option.textContent = pair;
        selectEl.appendChild(option);
      });
      
      console.log('Admin: 加载了', tradingPairs.length, '个交易对');
      
    } catch (err) {
      console.error('Admin: 加载交易对失败:', err);
    }
  }
  */
  
  // 更新交易信息显示函数已在全局作用域定义
  
  // 初始化订单弹窗 (已删除一键下单功能)
  /*
  window.initOrderModal = function() {
    console.log('Admin: 初始化订单弹窗');
    
    // 设置数量输入框事件监听器
    var quantityInput = document.getElementById('order-quantity');
    if (quantityInput) {
      quantityInput.addEventListener('input', updateUSDTAmount);
    }
    
    // 设置订单类型变化监听器
    var orderTypeSelect = document.getElementById('order-type');
    if (orderTypeSelect) {
      orderTypeSelect.addEventListener('change', function() {
        togglePriceField();
      });
    }
    
    // 设置USDT金额切换事件监听器
    var usdtToggle = document.getElementById('usdt-amount-toggle');
    if (usdtToggle) {
      usdtToggle.addEventListener('change', function() {
        updateUSDTAmount();
      });
    }
    
    // 初始化显示
    togglePriceField();
    updateUSDTAmount();
  }
  */
  
  // 切换价格字段显示 (已删除一键下单功能)
  /*
  window.togglePriceField = function() {
    var orderType = document.getElementById('order-type');
    var priceGroup = document.getElementById('price-group');
    var priceInput = document.getElementById('order-price');
    
    if (orderType && priceGroup && priceInput) {
      var orderTypeValue = orderType.value;
      var showPrice = orderTypeValue === 'limit' || orderTypeValue === 'stop_limit';
      
      priceGroup.style.display = showPrice ? 'block' : 'none';
      
      if (showPrice && !priceInput.value) {
        // 为限价单设置默认价格（可以根据当前市场价格设置）
        priceInput.value = '104410.00'; // 示例BTC价格
      }
    }
  }
  */
  
  // 更新USDT金额显示 (已删除一键下单功能)
  /*
  window.updateUSDTAmount = function() {
    var quantityInput = document.getElementById('order-quantity');
    var usdtToggle = document.getElementById('usdt-amount-toggle');
    var amountDisplay = document.getElementById('usdt-amount-display');
    
    if (!quantityInput || !amountDisplay) return;
    
    var quantity = parseFloat(quantityInput.value) || 0;
    var isUSDTMode = usdtToggle ? usdtToggle.checked : false;
    
    if (isUSDTMode) {
      // 模拟价格计算（实际应该从API获取实时价格）
      var mockPrice = 104410; // 假设BTC价格为$104,410
      var usdtAmount = quantity * mockPrice;
      amountDisplay.textContent = '≈ ' + usdtAmount.toFixed(2) + ' USDT';
    } else {
      amountDisplay.textContent = '≈ 104.41 USDT';
    }
  }
  */
  
  // 收集订单数据 (已删除一键下单功能)
  /*
  window.collectOrderData = function() {
    var exchangeSelect = document.getElementById('trading-exchange');
    var pairSelect = document.getElementById('trading-pair');
    var orderType = document.getElementById('order-type');
    var orderSide = document.getElementById('order-side');
    var positionMode = document.getElementById('position-mode');
    var quantity = document.getElementById('order-quantity');
    var price = document.getElementById('order-price');
    
    if (!exchangeSelect || !pairSelect || !orderType || !orderSide || !positionMode || !quantity) {
      alert('订单数据不完整');
      return null;
    }
    
    if (selectedAccounts.size === 0) {
      alert('请至少选择一个账户');
      return null;
    }
    
    var quantityValue = parseFloat(quantity.value);
    if (isNaN(quantityValue) || quantityValue <= 0) {
      alert('请输入有效的数量（必须大于0）');
      return null;
    }
    
    var orderTypeValue = orderType.value;
    var needsPrice = orderTypeValue === 'limit' || orderTypeValue === 'stop_limit';
    
    if (needsPrice) {
      if (!price || !price.value) {
        alert('限价单和止损限价单需要输入价格');
        return null;
      }
      var priceValue = parseFloat(price.value);
      if (isNaN(priceValue) || priceValue <= 0) {
        alert('请输入有效的价格（必须大于0）');
        return null;
      }
    }
    
    var orderData = {
      accounts: Array.from(selectedAccounts),
      exchange: exchangeSelect.value,
      pair: pairSelect.value,
      type: orderTypeValue,
      side: orderSide.value,
      position_mode: positionMode.value,
      quantity: quantityValue,
      price: needsPrice ? parseFloat(price.value) : null
    };
    
    console.log('Admin: 收集到的订单数据:', orderData);
    return orderData;
  }
  */
  
  // 执行订单 (已删除一键下单功能)
  /*
  window.executeOrder = async function(orderData) {
    try {
      console.log('Admin: 执行多账户订单:', orderData);
      
      // 显示加载状态
      var placeOrderBtn = document.getElementById('place-order-btn');
      if (placeOrderBtn) {
        placeOrderBtn.disabled = true;
        placeOrderBtn.innerHTML = '<span class="btn-icon">⏳</span>下单中...';
      }
      
      var successCount = 0;
      var errorCount = 0;
      var errors = [];
      
      // 为每个选中的账户执行下单
      for (var i = 0; i < orderData.accounts.length; i++) {
        var accountId = orderData.accounts[i];
        var account = availableAccounts.find(function(acc) { return acc.id === accountId; });
        
        try {
          console.log('Admin: 为账户下单:', account ? account.email : accountId);
          
          // 构建广播下单请求 - 根据API文档格式
          var broadcastData = {
            script_id: null, // 管理员下单不需要script_id
            symbol: orderData.pair,
            side: orderData.side,
            order_type: orderData.type,
            quantity: orderData.quantity,
            price: orderData.price, // 根据订单类型设置价格
            position_mode: orderData.position_mode,
            exchange: orderData.exchange,
            user_id: accountId, // 指定用户ID
            // 根据API文档添加其他必要字段
            connector_name: orderData.exchange, // 连接器名称
            account_name: account ? account.email : accountId, // 账户名称
            time_in_force: orderData.type === 'market' ? 'IOC' : 'GTC', // 市价单使用IOC，其他使用GTC
            reduce_only: orderData.position_mode === 'close', // 关闭仓位时设为仅减仓
            post_only: orderData.type === 'limit', // 限价单可以设为仅做市
            client_order_id: 'admin_' + Date.now() + '_' + Math.random().toString(36).substr(2, 9) // 客户端订单ID
          };
          
          console.log('Admin: 构建的广播下单数据:', broadcastData);
          
          // 调用广播下单API
          var response = await request('POST', '/admin/broadcast', broadcastData, true);
          var result = await response.json();
          
          if (response.ok) {
            successCount++;
            console.log('Admin: 账户', account ? account.email : accountId, '下单成功:', result);
          } else {
            errorCount++;
            var errorMsg = result.message || result.detail || '下单失败';
            if (result.errors && Array.isArray(result.errors)) {
              errorMsg = result.errors.join(', ');
            }
            errors.push((account ? account.email : accountId) + ': ' + errorMsg);
            console.error('Admin: 账户', account ? account.email : accountId, '下单失败:', errorMsg, result);
          }
          
        } catch (err) {
          errorCount++;
          var errorMsg = err.message || '网络错误';
          errors.push((account ? account.email : accountId) + ': ' + errorMsg);
          console.error('Admin: 账户', account ? account.email : accountId, '下单异常:', err);
        }
      }
      
      // 显示结果
      if (successCount > 0 && errorCount === 0) {
        alert('所有账户下单成功！\n成功: ' + successCount + ' 个账户');
        closeOrderModal();
        closeTradingCenter();
      } else if (successCount > 0 && errorCount > 0) {
        alert('部分账户下单成功！\n成功: ' + successCount + ' 个账户\n失败: ' + errorCount + ' 个账户\n\n失败详情:\n' + errors.join('\n'));
      } else {
        throw new Error('所有账户下单失败！\n\n失败详情:\n' + errors.join('\n'));
      }
      
    } catch (err) {
      console.error('Admin: 多账户下单失败:', err);
      alert('下单失败: ' + err.message);
    } finally {
      // 恢复按钮状态
      var placeOrderBtn = document.getElementById('place-order-btn');
      if (placeOrderBtn) {
        placeOrderBtn.disabled = false;
        placeOrderBtn.innerHTML = '<span class="btn-icon">🚀</span>下订单';
      }
    }
  }
  */

  // 启动应用 - 只在admin.html页面执行
  console.log('Admin.js: 当前页面路径:', window.location.pathname);
  console.log('Admin.js: 是否为admin.html页面:', window.location.pathname.endsWith('admin.html') || window.location.pathname === '/admin.html');
  
  if (window.location.pathname.endsWith('admin.html') || window.location.pathname === '/admin.html') {
    console.log('Admin.js: 在admin.html页面，执行init()');
    init();
  } else {
    console.log('Admin.js: 不在admin.html页面，跳过init()');
  }
  
  // 添加返回按钮的事件监听器（备用方案） - 只在admin.html页面执行
  if (window.location.pathname.endsWith('admin.html') || window.location.pathname === '/admin.html') {
    document.addEventListener('DOMContentLoaded', function() {
      var backButton = document.querySelector('button[onclick="goToUserPage()"]');
      if (backButton) {
        console.log('Admin: 找到返回按钮，添加事件监听器');
        backButton.addEventListener('click', function(e) {
          e.preventDefault();
          console.log('Admin: 通过事件监听器点击返回按钮，准备退出登录');
          // 清除登录token
          localStorage.removeItem('token');
          console.log('Admin: 已清除登录token');
          // 跳转到用户界面
          window.location.href = 'index.html';
        });
      } else {
        console.log('Admin: 未找到返回按钮');
      }
    });
  }
})();

// 广播管理功能
var currentGroupId = null;

// 显示/隐藏数据源指示器
function showDataSourceIndicator(show) {
  var indicator = document.getElementById('data-source-indicator');
  if (indicator) {
    indicator.style.display = show ? 'flex' : 'none';
  }
}

// 打开广播管理弹窗
window.openBroadcastManager = function() {
  console.log('Admin: 打开广播管理');
  var modal = document.getElementById('broadcast-manager-modal');
  if (modal) {
    modal.style.display = 'block';
    loadBroadcastGroups();
    loadRiskConfig();
  }
};

// 关闭广播管理弹窗
window.closeBroadcastManager = function() {
  console.log('Admin: 关闭广播管理');
  var modal = document.getElementById('broadcast-manager-modal');
  if (modal) {
    modal.style.display = 'none';
  }
};

// 加载广播分组列表
window.loadBroadcastGroups = async function() {
  console.log('Admin: 加载广播分组列表');
  
  var groupsListDiv = document.getElementById('broadcast-groups-list');
  if (!groupsListDiv) return;
  
  try {
    // 调用管理员广播分组列表API
    var response = await request('GET', '/admin/groups');
    console.log('Admin: 广播分组API响应:', response);
    
    // 检查响应格式
    if (response && Array.isArray(response) && response.length > 0) {
      console.log('Admin: 使用真实API数据，分组数量:', response.length);
      showDataSourceIndicator(false); // 隐藏指示器
      renderBroadcastGroups(response);
    } else if (response && Array.isArray(response) && response.length === 0) {
      console.log('Admin: API返回空数组，显示空状态');
      showDataSourceIndicator(false); // 隐藏指示器
      groupsListDiv.innerHTML = '<p class="muted">暂无广播分组，点击上方按钮创建第一个分组</p>';
    } else {
      throw new Error('API返回数据格式不正确: ' + JSON.stringify(response));
    }
  } catch (err) {
    console.error('Admin: 加载广播分组API失败，使用模拟数据:', err);
    
    // 显示数据源指示器
    showDataSourceIndicator(true);
    
    // 检查是否是认证错误
    if (err.message && err.message.includes('Not authenticated')) {
      console.log('Admin: 检测到认证错误，使用模拟数据演示功能');
    }
    
    // 使用模拟数据
    var mockGroups = [
      {
        id: 1,
        name: 'VIP交易信号',
        description: '高级交易策略信号，适合有经验的交易者',
        type: 'vip',
        member_count: 15,
        created_at: new Date(Date.now() - 86400000).toISOString()
      },
      {
        id: 2,
        name: '新手指导组',
        description: '适合新手的交易指导和基础策略',
        type: 'public',
        member_count: 45,
        created_at: new Date(Date.now() - 172800000).toISOString()
      },
      {
        id: 3,
        name: '量化交易组',
        description: '量化交易策略和算法分享',
        type: 'private',
        member_count: 28,
        created_at: new Date(Date.now() - 259200000).toISOString()
      }
    ];
    
    renderBroadcastGroups(mockGroups);
  }
}

// 渲染广播分组列表
window.renderBroadcastGroups = function(groups) {
  var groupsListDiv = document.getElementById('broadcast-groups-list');
  if (!groupsListDiv) return;
  
  if (!groups || groups.length === 0) {
    groupsListDiv.innerHTML = '<p class="muted">暂无广播分组</p>';
    return;
  }
  
  var html = '';
  groups.forEach(function(group) {
    var typeIcon = {
      'public': '🌐',
      'private': '🔒',
      'vip': '👑'
    }[group.type] || '📁';
    
    var createdTime = new Date(group.created_at).toLocaleDateString('zh-CN');
    
    html += '<div class="broadcast-group-item admin">';
    html += '<div class="group-header">';
    html += '<span class="group-type">' + typeIcon + '</span>';
    html += '<span class="group-name">' + group.name + '</span>';
    html += '<span class="group-member-count">' + group.member_count + ' 人</span>';
    html += '</div>';
    html += '<div class="group-description">' + group.description + '</div>';
    html += '<div class="group-meta">';
    html += '<span class="group-created">创建时间: ' + createdTime + '</span>';
    html += '</div>';
    html += '<div class="group-actions">';
    html += '<button class="btn primary" onclick="viewGroupDetail(' + group.id + ')">查看详情</button>';
    html += '<button class="btn secondary" onclick="editGroup(' + group.id + ')">编辑</button>';
    html += '<button class="btn danger" onclick="deleteGroup(' + group.id + ')">删除</button>';
    html += '</div>';
    html += '</div>';
  });
  
  groupsListDiv.innerHTML = html;
}

// 查看分组详情
window.viewGroupDetail = function(groupId) {
  console.log('Admin: 查看分组详情:', groupId);
  currentGroupId = groupId;
  
  var modal = document.getElementById('group-detail-modal');
  if (modal) {
    modal.style.display = 'block';
    loadGroupDetail(groupId);
  }
};

// 加载分组详情
window.loadGroupDetail = async function(groupId) {
  console.log('Admin: 加载分组详情:', groupId);
  
  var titleEl = document.getElementById('group-detail-title');
  var subtitleEl = document.getElementById('group-detail-subtitle');
  var membersListDiv = document.getElementById('group-members-list');
  
  try {
    // 调用分组详情API
    var response = await request('GET', '/admin/groups/' + groupId);
    console.log('Admin: 分组详情API响应:', response);
    
    if (response && response.id) {
      console.log('Admin: 使用真实API数据');
      if (titleEl) titleEl.textContent = response.name || '分组详情';
      if (subtitleEl) subtitleEl.textContent = response.description || '管理分组成员';
      
      // 加载分组成员
      loadGroupMembers(groupId);
    } else {
      throw new Error('API返回数据格式不正确: ' + JSON.stringify(response));
    }
  } catch (err) {
    console.error('Admin: 加载分组详情API失败，使用模拟数据:', err);
    
    // 使用模拟数据
    if (titleEl) titleEl.textContent = '分组详情';
    if (subtitleEl) subtitleEl.textContent = '管理分组成员';
    loadGroupMembers(groupId);
  }
}

// 加载分组成员
window.loadGroupMembers = async function(groupId) {
  console.log('Admin: 加载分组成员:', groupId);
  
  var membersListDiv = document.getElementById('group-members-list');
  if (!membersListDiv) return;
  
  try {
    // 这里应该调用获取分组成员的API，但API文档中没有明确的接口
    // 使用模拟数据
    var mockMembers = [
      {
        account_name: 'user1@example.com',
        role: 'member',
        joined_at: new Date(Date.now() - 86400000).toISOString(),
        status: 'active'
      },
      {
        account_name: 'user2@example.com',
        role: 'member',
        joined_at: new Date(Date.now() - 172800000).toISOString(),
        status: 'active'
      },
      {
        account_name: 'user3@example.com',
        role: 'member',
        joined_at: new Date(Date.now() - 259200000).toISOString(),
        status: 'inactive'
      }
    ];
    
    renderGroupMembers(mockMembers);
  } catch (err) {
    console.error('Admin: 加载分组成员失败:', err);
    membersListDiv.innerHTML = '<p class="muted">加载失败，请稍后重试</p>';
  }
}

// 渲染分组成员
window.renderGroupMembers = function(members) {
  var membersListDiv = document.getElementById('group-members-list');
  if (!membersListDiv) return;
  
  if (!members || members.length === 0) {
    membersListDiv.innerHTML = '<p class="muted">暂无成员</p>';
    return;
  }
  
  var html = '';
  members.forEach(function(member) {
    var statusClass = member.status === 'active' ? 'success' : 'warning';
    var joinedTime = new Date(member.joined_at).toLocaleDateString('zh-CN');
    
    html += '<div class="member-item">';
    html += '<div class="member-info">';
    html += '<span class="member-name">' + member.account_name + '</span>';
    html += '<span class="member-role">' + member.role + '</span>';
    html += '</div>';
    html += '<div class="member-meta">';
    html += '<span class="member-status ' + statusClass + '">' + member.status + '</span>';
    html += '<span class="member-joined">加入时间: ' + joinedTime + '</span>';
    html += '</div>';
    html += '<div class="member-actions">';
    html += '<button class="btn danger" onclick="removeMember(\'' + member.account_name + '\')">移除</button>';
    html += '</div>';
    html += '</div>';
  });
  
  membersListDiv.innerHTML = html;
}

// 关闭分组详情弹窗
window.closeGroupDetailModal = function() {
  console.log('Admin: 关闭分组详情');
  var modal = document.getElementById('group-detail-modal');
  if (modal) {
    modal.style.display = 'none';
  }
  currentGroupId = null;
};

// 打开创建分组弹窗
window.openCreateGroupModal = function() {
  console.log('Admin: 打开创建分组弹窗');
  var modal = document.getElementById('create-group-modal');
  if (modal) {
    modal.style.display = 'block';
  }
};

// 关闭创建分组弹窗
window.closeCreateGroupModal = function() {
  console.log('Admin: 关闭创建分组弹窗');
  var modal = document.getElementById('create-group-modal');
  if (modal) {
    modal.style.display = 'none';
    // 清空表单
    var nameInput = document.getElementById('group-name');
    var descInput = document.getElementById('group-description');
    var typeSelect = document.getElementById('group-type');
    if (nameInput) nameInput.value = '';
    if (descInput) descInput.value = '';
    if (typeSelect) typeSelect.value = 'public';
  }
};

// 创建广播分组
window.createBroadcastGroup = async function() {
  console.log('Admin: 创建广播分组');
  
  var nameInput = document.getElementById('group-name');
  var descInput = document.getElementById('group-description');
  var typeSelect = document.getElementById('group-type');
  
  if (!nameInput || !descInput || !typeSelect) {
    console.error('Admin: 创建分组表单元素未找到');
    return;
  }
  
  var name = nameInput.value.trim();
  var description = descInput.value.trim();
  var type = typeSelect.value;
  
  if (!name) {
    alert('请输入分组名称');
    return;
  }
  
  try {
    // 构建分组数据
    var groupData = {
      name: name,
      desc: description, // 使用 desc 而不是 description
      connector_name: type // 使用 connector_name 而不是 type
    };
    
    console.log('Admin: 创建分组数据:', groupData);
    
    // 调用创建分组API
    var response = await request('POST', '/admin/groups', groupData);
    console.log('Admin: 创建分组API响应:', response);
    
    if (response && (response.id || response.success !== false)) {
      alert('分组创建成功！');
      closeCreateGroupModal();
      loadBroadcastGroups(); // 重新加载分组列表
    } else {
      throw new Error('API返回失败状态: ' + JSON.stringify(response));
    }
  } catch (err) {
    console.error('Admin: 创建分组失败:', err);
    alert('创建分组失败: ' + err.message);
  }
};

// 删除分组
window.deleteGroup = async function(groupId) {
  console.log('Admin: 删除分组:', groupId);
  
  if (!confirm('确定要删除这个分组吗？此操作不可撤销。')) {
    return;
  }
  
  try {
    // 调用删除分组API
    var response = await request('DELETE', '/admin/groups/' + groupId);
    console.log('Admin: 删除分组API响应:', response);
    
    if (response && (response.success !== false || response.deleted !== false)) {
      alert('分组删除成功！');
      loadBroadcastGroups(); // 重新加载分组列表
    } else {
      throw new Error('API返回失败状态: ' + JSON.stringify(response));
    }
  } catch (err) {
    console.error('Admin: 删除分组失败:', err);
    alert('删除分组失败: ' + err.message);
  }
};

// 删除当前分组
window.deleteCurrentGroup = function() {
  if (currentGroupId) {
    deleteGroup(currentGroupId);
    closeGroupDetailModal();
  }
};

// 移除成员
window.removeMember = async function(accountName) {
  console.log('Admin: 移除成员:', accountName);
  
  if (!confirm('确定要移除这个成员吗？')) {
    return;
  }
  
  if (!currentGroupId) {
    alert('分组ID未找到');
    return;
  }
  
  try {
    // 调用移除成员API
    var response = await request('DELETE', '/admin/groups/' + currentGroupId + '/members/' + accountName);
    console.log('Admin: 移除成员API响应:', response);
    
    if (response && (response.success !== false || response.removed !== false)) {
      alert('成员移除成功！');
      loadGroupMembers(currentGroupId); // 重新加载成员列表
    } else {
      throw new Error('API返回失败状态: ' + JSON.stringify(response));
    }
  } catch (err) {
    console.error('Admin: 移除成员失败:', err);
    alert('移除成员失败: ' + err.message);
  }
};

// 加载风控配置
window.loadRiskConfig = async function() {
  console.log('Admin: 加载风控配置');
  
  var configDiv = document.getElementById('risk-config-content');
  if (!configDiv) return;
  
  try {
    // 调用风控配置API
    var response = await request('GET', '/admin/risk-config');
    console.log('Admin: 风控配置API响应:', response);
    
    if (response && typeof response === 'object') {
      console.log('Admin: 使用真实API数据');
      renderRiskConfig(response);
    } else {
      throw new Error('API返回数据格式不正确: ' + JSON.stringify(response));
    }
  } catch (err) {
    console.error('Admin: 加载风控配置API失败，使用模拟数据:', err);
    
    // 检查是否是认证错误
    if (err.message && err.message.includes('Not authenticated')) {
      console.log('Admin: 检测到认证错误，使用模拟数据演示功能');
    }
    
    // 使用模拟数据
    var mockConfig = {
      max_broadcast_per_hour: 10,
      max_members_per_group: 100,
      enable_auto_approval: true,
      risk_level: 'medium'
    };
    
    renderRiskConfig(mockConfig);
  }
};

// 渲染风控配置
window.renderRiskConfig = function(config) {
  var configDiv = document.getElementById('risk-config-content');
  if (!configDiv) return;
  
  var html = '<div class="risk-config-grid">';
  html += '<div class="config-item">';
  html += '<label>每小时最大广播数</label>';
  html += '<span class="config-value">' + (config.max_broadcast_per_hour || 10) + '</span>';
  html += '</div>';
  html += '<div class="config-item">';
  html += '<label>每组最大成员数</label>';
  html += '<span class="config-value">' + (config.max_members_per_group || 100) + '</span>';
  html += '</div>';
  html += '<div class="config-item">';
  html += '<label>自动审批</label>';
  html += '<span class="config-value">' + (config.enable_auto_approval ? '启用' : '禁用') + '</span>';
  html += '</div>';
  html += '<div class="config-item">';
  html += '<label>风险等级</label>';
  html += '<span class="config-value">' + (config.risk_level || 'medium') + '</span>';
  html += '</div>';
  html += '</div>';
  
  configDiv.innerHTML = html;
}

// 订单历史功能
window.openOrderHistory = function() {
  console.log('Admin: 打开订单历史');
  var modal = document.getElementById('order-history-modal');
  if (modal) {
    modal.style.display = 'block';
    loadOrderHistory();
  }
};

window.closeOrderHistory = function() {
  console.log('Admin: 关闭订单历史');
  var modal = document.getElementById('order-history-modal');
  if (modal) {
    modal.style.display = 'none';
  }
};

// 加载订单历史
window.loadOrderHistory = async function() {
  console.log('Admin: 加载订单历史');
  
  var historyListDiv = document.getElementById('order-history-list');
  if (!historyListDiv) return;
  
  try {
    historyListDiv.innerHTML = '<div class="loading">加载中...</div>';
    
    // 使用模拟数据（API接口不存在，避免404错误）
    console.log('Admin: 使用模拟订单历史数据');
    
    var mockOrders = [
      {
        id: 'admin_1234567890_abc123',
        symbol: 'BTC-USDT',
        side: 'buy',
        order_type: 'market',
        quantity: 0.001,
        price: null,
        status: 'filled',
        exchange: 'gate_io',
        account_name: 'user1@example.com',
        created_at: new Date(Date.now() - 300000).toISOString(),
        filled_at: new Date(Date.now() - 280000).toISOString()
      },
      {
        id: 'admin_1234567891_def456',
        symbol: 'ETH-USDT',
        side: 'sell',
        order_type: 'limit',
        quantity: 0.1,
        price: 3500.0,
        status: 'pending',
        exchange: 'gate_io',
        account_name: 'user2@example.com',
        created_at: new Date(Date.now() - 600000).toISOString(),
        filled_at: null
      }
    ];
    
    renderOrderHistory(mockOrders);
  } catch (err) {
    console.error('Admin: 加载订单历史失败:', err);
    
    // 使用模拟数据
    var mockOrders = [
      {
        id: 'admin_1234567890_abc123',
        symbol: 'BTC-USDT',
        side: 'buy',
        order_type: 'market',
        quantity: 0.001,
        price: null,
        status: 'filled',
        exchange: 'gate_io',
        account_name: 'user1@example.com',
        created_at: new Date(Date.now() - 300000).toISOString(),
        filled_at: new Date(Date.now() - 280000).toISOString()
      },
      {
        id: 'admin_1234567891_def456',
        symbol: 'ETH-USDT',
        side: 'sell',
        order_type: 'limit',
        quantity: 0.1,
        price: 3200.50,
        status: 'pending',
        exchange: 'gate_io',
        account_name: 'user2@example.com',
        created_at: new Date(Date.now() - 600000).toISOString(),
        filled_at: null
      }
    ];
    
    renderOrderHistory(mockOrders);
  }
};

// 渲染订单历史
window.renderOrderHistory = function(orders) {
  var historyListDiv = document.getElementById('order-history-list');
  if (!historyListDiv) return;
  
  if (!orders || orders.length === 0) {
    historyListDiv.innerHTML = '<p class="muted">暂无订单记录</p>';
    return;
  }
  
  var html = '';
  orders.forEach(function(order) {
    var statusClass = {
      'filled': 'success',
      'pending': 'warning',
      'cancelled': 'error',
      'failed': 'error'
    }[order.status] || 'info';
    
    var sideClass = order.side === 'buy' ? 'buy' : 'sell';
    var sideText = order.side === 'buy' ? '买入' : '卖出';
    var typeText = {
      'market': '市价单',
      'limit': '限价单',
      'stop': '止损单',
      'stop_limit': '止损限价单'
    }[order.order_type] || order.order_type;
    
    var createdTime = new Date(order.created_at).toLocaleString('zh-CN');
    var filledTime = order.filled_at ? new Date(order.filled_at).toLocaleString('zh-CN') : '-';
    
    html += '<div class="order-history-item">';
    html += '<div class="order-header">';
    html += '<div class="order-symbol">' + order.symbol + '</div>';
    html += '<div class="order-side ' + sideClass + '">' + sideText + '</div>';
    html += '<div class="order-status ' + statusClass + '">' + order.status + '</div>';
    html += '</div>';
    html += '<div class="order-details">';
    html += '<div class="order-info">';
    html += '<span><strong>类型:</strong> ' + typeText + '</span>';
    html += '<span><strong>数量:</strong> ' + order.quantity + '</span>';
    if (order.price) {
      html += '<span><strong>价格:</strong> ' + order.price + '</span>';
    }
    html += '<span><strong>交易所:</strong> ' + order.exchange + '</span>';
    html += '</div>';
    html += '<div class="order-meta">';
    html += '<span><strong>账户:</strong> ' + order.account_name + '</span>';
    html += '<span><strong>订单ID:</strong> ' + order.id + '</span>';
    html += '</div>';
    html += '<div class="order-times">';
    html += '<span><strong>创建时间:</strong> ' + createdTime + '</span>';
    html += '<span><strong>成交时间:</strong> ' + filledTime + '</span>';
    html += '</div>';
    html += '</div>';
    html += '</div>';
  });
  
  historyListDiv.innerHTML = html;
}

// 策略管理功能
var strategyState = { 
  page: 1, 
  page_size: 10, 
  name: '', 
  symbol: '', 
  market_type: '', 
  status: '', 
  order: 'desc' 
};

// 打开策略管理
window.openStrategyManager = function() {
  console.log('Admin: 打开策略管理');
  var modal = document.getElementById('strategy-manager-modal');
  if (modal) {
    modal.style.display = 'block';
    loadStrategyStats();
    loadStrategyList();
    buildStrategyFilterBar();
  }
};

// 关闭策略管理
window.closeStrategyManager = function() {
  console.log('Admin: 关闭策略管理');
  var modal = document.getElementById('strategy-manager-modal');
  if (modal) {
    modal.style.display = 'none';
  }
};

// 加载策略统计
window.loadStrategyStats = async function() {
  console.log('Admin: 加载策略统计');
  
  var statsDiv = document.getElementById('strategy-stats-content');
  if (!statsDiv) return;
  
  try {
    statsDiv.innerHTML = '<div class="loading">加载中...</div>';
    
    // 调用管理员策略列表API获取统计数据: GET /scripts
    console.log('Admin: 调用策略统计API: GET /scripts');
    var response = await request('GET', '/scripts', null, true);
    var scriptsData = await response.json();
    
    console.log('Admin: 策略统计API响应:', scriptsData);
    
    if (response.ok) {
      // 处理API返回的数据格式
      var items = Array.isArray(scriptsData) ? scriptsData : (scriptsData.items || scriptsData.data || []);
      
      if (items && items.length > 0) {
        renderStrategyStats(items);
      } else {
        // 如果没有数据，显示空状态
        renderStrategyStats([]);
      }
    } else {
      throw new Error(scriptsData.message || scriptsData.detail || '获取策略统计失败');
    }
  } catch (err) {
    console.error('Admin: 加载策略统计失败:', err);
    
    // 显示错误信息
    statsDiv.innerHTML = '<p class="muted">统计加载失败: ' + err.message + '</p>';
    
    // 如果API失败，提供模拟数据用于演示
    console.log('Admin: 使用模拟统计数据');
    var mockStats = {
      totalStrategies: 8,
      activeStrategies: 6,
      pausedStrategies: 2,
      totalSymbols: 5
    };
    
    renderStrategyStats(mockStats);
  }
};

// 渲染策略统计
window.renderStrategyStats = function(data) {
  var statsDiv = document.getElementById('strategy-stats-content');
  if (!statsDiv) return;
  
  var stats = {};
  
  if (Array.isArray(data)) {
    // 从策略数据计算统计
    var totalStrategies = data.length;
    var activeStrategies = data.filter(function(script) { 
      return script.status === 'active' || script.enabled; 
    }).length;
    var pausedStrategies = totalStrategies - activeStrategies;
    var uniqueSymbols = new Set(data.map(function(script) { 
      return script.symbol; 
    })).size;
    
    stats = {
      totalStrategies: totalStrategies,
      activeStrategies: activeStrategies,
      pausedStrategies: pausedStrategies,
      totalSymbols: uniqueSymbols
    };
  } else {
    // 直接使用传入的统计数据
    stats = data;
  }
  
  var html = '<div class="risk-config-grid">';
  html += '<div class="config-item">';
  html += '<label>总策略数</label>';
  html += '<span class="config-value">' + (stats.totalStrategies || 0) + '</span>';
  html += '</div>';
  html += '<div class="config-item">';
  html += '<label>活跃策略</label>';
  html += '<span class="config-value">' + (stats.activeStrategies || 0) + '</span>';
  html += '</div>';
  html += '<div class="config-item">';
  html += '<label>暂停策略</label>';
  html += '<span class="config-value">' + (stats.pausedStrategies || 0) + '</span>';
  html += '</div>';
  html += '<div class="config-item">';
  html += '<label>交易符号数</label>';
  html += '<span class="config-value">' + (stats.totalSymbols || 0) + '</span>';
  html += '</div>';
  html += '<div class="config-item">';
  html += '<label>活跃率</label>';
  html += '<span class="config-value">' + (stats.totalStrategies > 0 ? Math.round((stats.activeStrategies / stats.totalStrategies) * 100) : 0) + '%</span>';
  html += '</div>';
  html += '</div>';
  
  statsDiv.innerHTML = html;
};

// 加载策略列表
window.loadStrategyList = async function() {
  console.log('Admin: 加载策略列表');
  
  var listDiv = document.getElementById('strategy-list-content');
  if (!listDiv) return;
  
  try {
    listDiv.innerHTML = '<p class="muted">加载中...</p>';
    
    // 构建查询参数 - 与admin_strategy_manager.js保持一致
    var q = [];
    if (strategyState.page) q.push('page=' + encodeURIComponent(strategyState.page));
    if (strategyState.page_size) q.push('page_size=' + encodeURIComponent(strategyState.page_size));
    if (strategyState.name) q.push('name=' + encodeURIComponent(strategyState.name));
    if (strategyState.symbol) q.push('symbol=' + encodeURIComponent(strategyState.symbol));
    if (strategyState.market_type) q.push('market_type=' + encodeURIComponent(strategyState.market_type));
    if (strategyState.status) q.push('status=' + encodeURIComponent(strategyState.status));
    // 后端默认按 created_at 排序；追加 order=asc|desc 控制
    if (strategyState.order) q.push('order=' + encodeURIComponent(strategyState.order));
    
    var path = '/scripts' + (q.length ? ('?' + q.join('&')) : '');
    
    console.log('Admin: 调用策略列表API:', path);
    var response = await request('GET', path, null, true);
    var data = await response.json();
    
    console.log('Admin: 策略列表API响应:', data);
    
    if (response.ok) {
      var items = Array.isArray(data) ? data : (data.items || []);
      renderStrategyList(items);
      renderStrategyPager(data);
    } else {
      throw new Error(data.message || data.detail || '获取策略列表失败');
    }
  } catch (err) {
    console.error('Admin: 加载策略列表失败:', err);
    
    // 显示错误信息
    listDiv.innerHTML = '<p class="muted">加载失败</p>';
    
    // 如果API失败，提供模拟数据用于演示
    console.log('Admin: 使用模拟数据');
    var mockStrategies = [
      {
        id: 1,
        name: '趋势跟随策略',
        symbol: 'BTC-USDT',
        market_type: 'spot',
        status: 'active',
        enabled: true,
        created_at: new Date(Date.now() - 86400000).toISOString()
      },
      {
        id: 2,
        name: '均值回归策略',
        symbol: 'ETH-USDT',
        market_type: 'perpetual',
        status: 'paused',
        enabled: false,
        created_at: new Date(Date.now() - 172800000).toISOString()
      },
      {
        id: 3,
        name: '动量突破策略',
        symbol: 'BNB-USDT',
        market_type: 'spot',
        status: 'active',
        enabled: true,
        created_at: new Date(Date.now() - 259200000).toISOString()
      }
    ];
    
    renderStrategyList(mockStrategies);
  }
};

// 渲染策略列表
window.renderStrategyList = function(strategies) {
  var listDiv = document.getElementById('strategy-list-content');
  if (!listDiv) return;
  
  listDiv.innerHTML = '';
  if (!strategies || strategies.length === 0) {
    listDiv.innerHTML = '<p class="muted">暂无策略</p>';
    return;
  }
  
  // 使用与admin_strategy_manager.js相同的渲染逻辑
  for (var i = 0; i < strategies.length; i++) {
    (function(strategy) {
      // 创建策略卡片容器
      var wrap = document.createElement('section');
      wrap.className = 'card strategy-item';
      
      // 创建头部
      var header = document.createElement('div');
      header.style.display = 'flex';
      header.style.justifyContent = 'space-between';
      header.style.alignItems = 'center';
      
      var title = document.createElement('div');
      title.textContent = (strategy.name || '未命名') + ' · ' + (strategy.symbol || '');
      
      var actions = document.createElement('div');
      var toggleBtn = document.createElement('button');
      toggleBtn.className = 'btn';
      toggleBtn.textContent = '展开';
      actions.appendChild(toggleBtn);
      
      header.appendChild(title);
      header.appendChild(actions);
      wrap.appendChild(header);
      
      // 创建主体
      var body = document.createElement('div');
      body.style.display = 'none';
      body.style.marginTop = '8px';
      body.id = 'strategy-body-' + strategy.id;
      
      // 添加策略字段
      body.appendChild(buildRow('名称', strategy.name));
      body.appendChild(buildRow('符号', strategy.symbol));
      body.appendChild(buildRow('市场类型', strategy.market_type));
      
      // 状态使用滑块（开关）
      (function() {
        var f = document.createElement('div');
        f.className = 'field';
        var l = document.createElement('label');
        l.textContent = '状态';
        var wrapSwitch = document.createElement('div');
        wrapSwitch.style.display = 'flex';
        wrapSwitch.style.alignItems = 'center';
        wrapSwitch.style.gap = '8px';
        var sw = document.createElement('input');
        sw.type = 'checkbox';
        sw.setAttribute('role', 'switch');
        sw.checked = (strategy.status === 'active' || strategy.enabled);
        sw.disabled = true;
        var swLabel = document.createElement('span');
        swLabel.textContent = sw.checked ? '启用' : '停用';
        wrapSwitch.appendChild(sw);
        wrapSwitch.appendChild(swLabel);
        f.appendChild(l);
        f.appendChild(wrapSwitch);
        body.appendChild(f);
      })();
      
      body.appendChild(buildRow('创建时间', strategy.created_at));
      
      // 操作按钮
      var rowBtns = document.createElement('div');
      rowBtns.style.display = 'flex';
      rowBtns.style.gap = '8px';
      
      var btnEdit = document.createElement('button');
      btnEdit.className = 'btn';
      btnEdit.textContent = '修改';
      
      var btnDelete = document.createElement('button');
      btnDelete.className = 'btn';
      btnDelete.textContent = '删除';
      
      var btnReveal = document.createElement('button');
      btnReveal.className = 'btn';
      btnReveal.textContent = '查看秘钥';

      var btnToggle = document.createElement('button');
      btnToggle.className = 'btn ' + (strategy.status === 'active' ? 'btn-danger' : 'btn-success');
      btnToggle.textContent = strategy.status === 'active' ? '暂停' : '启用';
      btnToggle.addEventListener('click', async function() {
        var action = strategy.status === 'active' ? 'pause' : 'resume';
        btnToggle.disabled = true;
        try {
          await toggleStrategyStatus(strategy.id, action);
          strategy.status = action === 'pause' ? 'paused' : 'active';
          btnToggle.className = 'btn ' + (strategy.status === 'active' ? 'btn-danger' : 'btn-success');
          btnToggle.textContent = strategy.status === 'active' ? '暂停' : '启用';
        } finally {
          btnToggle.disabled = false;
        }
      });
      
      rowBtns.appendChild(btnEdit);
      rowBtns.appendChild(btnDelete);
      rowBtns.appendChild(btnReveal);
      rowBtns.appendChild(btnToggle);
      body.appendChild(rowBtns);
      wrap.appendChild(body);
      
      // 展开/收起功能
      toggleBtn.addEventListener('click', function() {
        var open = body.style.display !== 'none';
        body.style.display = open ? 'none' : '';
        toggleBtn.textContent = open ? '展开' : '收起';
      });
      
      // 删除功能
      btnDelete.addEventListener('click', async function() {
        if (!confirm('确认删除该策略？')) return;
        try {
          var response = await request('DELETE', '/scripts/' + strategy.id, null, true);
          if (response.ok || (response.status && response.status < 400)) {
            loadStrategyList();
            loadStrategyStats();
            return;
          }
          // fallback: 部分后端可能使用 POST /scripts/{id}/delete
          var fallbackResponse = await request('POST', '/scripts/' + strategy.id + '/delete', {}, true);
          var fallbackResult = await fallbackResponse.json();
          if (fallbackResponse.ok) {
            loadStrategyList();
            loadStrategyStats();
          }
        } catch (err) {
          console.error('Admin: 删除策略失败:', err);
        }
      });
      
      // 编辑功能
      btnEdit.addEventListener('click', function() {
        window.location.href = 'strategy-detail.html?id=' + encodeURIComponent(strategy.id);
      });
      
      // 查看密钥（跳转）
      btnReveal.addEventListener('click', function() {
        window.location.href = 'strategy-secret.html?id=' + encodeURIComponent(strategy.id);
      });
      
      listDiv.appendChild(wrap);
    })(strategies[i]);
  }
};

// 创建策略字段的辅助函数 - 与admin_strategy_manager.js保持一致
function buildRow(label, value) {
  var d = document.createElement('div');
  d.className = 'field';
  var l = document.createElement('label');
  l.textContent = label;
  var i = document.createElement('input');
  i.className = 'input';
  i.value = value == null ? '' : String(value);
  i.readOnly = true;
  d.appendChild(l);
  d.appendChild(i);
  return d;
}

// 创建策略字段的辅助函数（保留兼容性）
function createStrategyField(label, value) {
  return buildRow(label, value);
}

// 表单字段创建函数 - 与admin_strategy_manager.js保持一致
function formField(label, id, opts) {
  var f = document.createElement('div');
  f.className = 'field';
  var l = document.createElement('label');
  l.setAttribute('for', id);
  l.textContent = label;
  var el = null;
  if (opts && opts.type === 'select') {
    el = document.createElement('select');
    el.className = 'input';
    el.id = id;
    var o1 = document.createElement('option');
    o1.value = 'spot';
    o1.textContent = 'spot（现货）';
    var o2 = document.createElement('option');
    o2.value = 'perpetual';
    o2.textContent = 'perpetual（合约）';
    el.appendChild(o1);
    el.appendChild(o2);
  } else {
    el = document.createElement('input');
    el.className = 'input';
    el.id = id;
    if (opts && opts.placeholder) el.placeholder = opts.placeholder;
  }
  f.appendChild(l);
  f.appendChild(el);
  return { wrap: f, input: el };
}

// 切换策略详情显示
window.toggleStrategyDetails = function(strategyId, button) {
  var body = document.getElementById('strategy-body-' + strategyId);
  
  if (body && button) {
    var isExpanded = body.classList.contains('expanded');
    if (isExpanded) {
      body.classList.remove('expanded');
      button.textContent = '展开';
    } else {
      body.classList.add('expanded');
      button.textContent = '收起';
    }
  }
};

// 切换策略状态
window.toggleStrategyStatus = async function(strategyId, action) {
  if (!strategyId || (action !== 'pause' && action !== 'resume')) return;
  var path = '/scripts/' + strategyId + (action === 'resume' ? '/resume' : '/pause');
  var actionText = action === 'resume' ? '恢复' : '暂停';
  console.log('Admin: 调用策略状态API:', path, '操作:', actionText);
  try {
    var response = await request('POST', path, {}, true);
    var result = await response.json();
    console.log('Admin: 策略状态API响应:', result);
    if (!response.ok) {
      throw new Error(result.message || result.detail || actionText + '策略失败');
    }
    setTimeout(function() {
      loadStrategyStats();
      loadStrategyList();
    }, 500);
  } catch (err) {
    console.error('Admin: 切换策略状态失败:', err);
    alert('操作失败: ' + err.message);
  }
};

// 编辑策略
window.editStrategy = function(strategyId) {
  console.log('Admin: 跳转编辑策略页面:', strategyId);
  if (strategyId == null) return;
  window.location.href = 'strategy-detail.html?id=' + encodeURIComponent(strategyId);
};

// 删除策略
window.deleteStrategy = async function(strategyId) {
  console.log('Admin: 删除策略:', strategyId);
  
  if (!confirm('确认删除该策略？此操作不可撤销！')) return;
  
  try {
    // 删除策略: DELETE /scripts/{script_id}
    console.log('Admin: 调用删除策略API: DELETE /scripts/' + strategyId);
    var response = await request('DELETE', '/scripts/' + strategyId, null, true);
    var result = null;
    try {
      result = await response.json();
    } catch (_) {
      result = null;
    }

    console.log('Admin: 删除策略API响应:', result);

    if (response.ok || (response.status && response.status < 400)) {
      alert('策略删除成功！');
      console.log('Admin: 策略删除成功');

      // 重新加载列表和统计
      loadStrategyList();
      loadStrategyStats();
    } else {
      throw new Error((result && (result.message || result.detail)) || '删除策略失败');
    }
  } catch (err) {
    console.error('Admin: 删除策略失败:', err);
    alert('删除策略失败: ' + err.message);
  }
};

// 显示策略密钥
window.revealStrategySecret = function(strategyId) {
  console.log('Admin: 跳转策略秘钥页面:', strategyId);
  if (strategyId == null) return;
  window.location.href = 'strategy-secret.html?id=' + encodeURIComponent(strategyId);
};

// 显示策略密钥内容 - 与admin_strategy_manager.js保持一致
function showReveal(container, data, item) {
  if (!data) return;
  if (container && container.style.display === 'none') {
    container.style.display = '';
  }
  
  // 展示格式化 Webhook URL：使用当前来源 + 后端返回的 webhook_url（路径）
  var origin = location.origin || (location.protocol + '//' + location.host);
  var path = data.webhook_url || '';
  var webhookUrl = origin.replace(/\/$/, '') + (path ? (path.startsWith('/') ? path : ('/' + path)) : '');
  
  // 查找或创建单一结果盒
  var box = container.querySelector('[data-reveal-box="reveal-box"]');
  if (!box) {
    box = document.createElement('div');
    box.setAttribute('data-reveal-box', 'reveal-box');
    box.className = 'card';
    box.style.marginTop = '8px';
    container.appendChild(box);
  }
  box.innerHTML = '';
  
  var h = document.createElement('h4');
  h.className = 'card-title';
  h.textContent = '新口令（已旋转）';
  box.appendChild(h);
  
  function copyRow(label, value) {
    var f = document.createElement('div');
    f.className = 'field';
    var l = document.createElement('label');
    l.textContent = label;
    var i = document.createElement('input');
    i.className = 'input';
    i.readOnly = true;
    i.value = value || '';
    var b = document.createElement('button');
    b.className = 'btn';
    b.type = 'button';
    b.textContent = '复制';
    b.addEventListener('click', function() {
      if (navigator.clipboard) {
        navigator.clipboard.writeText(i.value);
      } else {
        try {
          i.select();
          document.execCommand('copy');
        } catch (_) {}
      }
    });
    f.appendChild(l);
    f.appendChild(i);
    f.appendChild(b);
    box.appendChild(f);
  }
  
  copyRow('Webhook URL', webhookUrl);
  
  if (data.body_secret) {
    var jsonStr = JSON.stringify({ secret: data.body_secret }, null, 2);
    // 使用 textarea 便于显示多行 JSON
    var f = document.createElement('div');
    f.className = 'field';
    var l = document.createElement('label');
    l.textContent = 'Body Secret（JSON）';
    var ta = document.createElement('textarea');
    ta.className = 'input';
    ta.rows = 3;
    ta.readOnly = true;
    ta.value = jsonStr;
    var b = document.createElement('button');
    b.className = 'btn';
    b.type = 'button';
    b.textContent = '复制';
    b.addEventListener('click', function() {
      if (navigator.clipboard) {
        navigator.clipboard.writeText(jsonStr);
      } else {
        try {
          ta.select();
          document.execCommand('copy');
        } catch (_) {}
      }
    });
    f.appendChild(l);
    f.appendChild(ta);
    f.appendChild(b);
    box.appendChild(f);
  }
  
  var tip = document.createElement('p');
  tip.className = 'muted small';
  tip.textContent = '提示：旧口令已失效，请尽快更新 TradingView 配置。';
  box.appendChild(tip);
}

// 显示策略密钥内容（保留兼容性）
function showStrategyReveal(strategyId, data) {
  var body = document.getElementById('strategy-body-' + strategyId);
  if (body) {
    showReveal(body, data, null);
  }
};

// 复制到剪贴板
window.copyToClipboard = function(element) {
  if (navigator.clipboard && navigator.clipboard.writeText) {
    navigator.clipboard.writeText(element.value).then(function() {
      alert('已复制到剪贴板');
    }, function() {
      alert('复制失败');
    });
  } else {
    try {
      element.select();
      document.execCommand('copy');
      alert('已复制到剪贴板');
    } catch (err) {
      alert('复制失败');
    }
  }
};

var STRATEGY_PARENT_SENTINEL = '__unset__';

function lockStrategyParentModal(modal) {
  if (!modal) return;
  var parentModal = document.getElementById('strategy-manager-modal');
  if (!parentModal || parentModal.style.display === 'none') return;
  modal.dataset.parentModalId = parentModal.id;
  modal.dataset.prevParentPointer =
    parentModal.style.pointerEvents && parentModal.style.pointerEvents.length
      ? parentModal.style.pointerEvents
      : STRATEGY_PARENT_SENTINEL;
  modal.dataset.prevParentZIndex =
    parentModal.style.zIndex && parentModal.style.zIndex.length
      ? parentModal.style.zIndex
      : STRATEGY_PARENT_SENTINEL;
  parentModal.style.pointerEvents = 'none';
  parentModal.style.zIndex = '1000';
}

function unlockStrategyParentModal(modal) {
  if (!modal) return;
  var parentId = modal.dataset.parentModalId;
  if (!parentId) return;
  var parentModal = document.getElementById(parentId);
  if (parentModal) {
    var prevPointer = modal.dataset.prevParentPointer;
    if (prevPointer && prevPointer !== STRATEGY_PARENT_SENTINEL) {
      parentModal.style.pointerEvents = prevPointer;
    } else {
      parentModal.style.removeProperty('pointer-events');
    }
    var prevZ = modal.dataset.prevParentZIndex;
    if (prevZ && prevZ !== STRATEGY_PARENT_SENTINEL) {
      parentModal.style.zIndex = prevZ;
    } else {
      parentModal.style.removeProperty('z-index');
    }
  }
  delete modal.dataset.parentModalId;
  delete modal.dataset.prevParentPointer;
  delete modal.dataset.prevParentZIndex;
}

function elevateStrategyFormModal(modal) {
  if (!modal) return;
  modal.dataset.prevZIndex =
    modal.style.zIndex && modal.style.zIndex.length
      ? modal.style.zIndex
      : STRATEGY_PARENT_SENTINEL;
  modal.style.zIndex = '1100';
}

function resetStrategyFormModalZ(modal) {
  if (!modal) return;
  var prevZ = modal.dataset.prevZIndex;
  if (prevZ && prevZ !== STRATEGY_PARENT_SENTINEL) {
    modal.style.zIndex = prevZ;
  } else if (prevZ !== undefined) {
    modal.style.removeProperty('z-index');
  }
  delete modal.dataset.prevZIndex;
}

// 打开创建策略表单
window.openCreateStrategyModal = function() {
  console.log('Admin: 跳转至策略创建页面');
  window.location.href = 'strategy-create.html';
};

// 打开策略表单 - 与admin_strategy_manager.js保持一致
function openStrategyForm(title, strategy) {
  var modal = document.getElementById('strategy-form-modal');
  var titleEl = document.getElementById('strategy-form-title');
  var subtitleEl = document.getElementById('strategy-form-subtitle');
  var contentEl = document.getElementById('strategy-form-content');
  
  if (!modal || !titleEl || !subtitleEl || !contentEl) return;
  
  titleEl.textContent = title || '创建策略';
  subtitleEl.textContent = strategy ? '编辑现有策略' : '创建新的交易策略';
  
  // 生成表单内容
  contentEl.innerHTML = '';
  
  // 使用与admin_strategy_manager.js相同的表单字段创建方式
  var fName = formField('策略名称', 'strategy-name', { placeholder: '如 趋势跟随' });
  var fSymbol = formField('交易符号', 'strategy-symbol', { placeholder: '如 BTC-USDT' });
  var fMarket = formField('市场类型', 'strategy-market', { type: 'select' });
  var msg = document.createElement('div');
  msg.className = 'form-msg';
  msg.id = 'strategy-form-msg';
  var row = document.createElement('div');
  row.style.display = 'flex';
  row.style.gap = '8px';
  var btnCancel = document.createElement('button');
  btnCancel.className = 'btn';
  btnCancel.type = 'button';
  btnCancel.textContent = '取消';
  var btnOk = document.createElement('button');
  btnOk.className = 'btn primary';
  btnOk.type = 'button';
  btnOk.textContent = '保存';
  
  contentEl.appendChild(fName.wrap);
  contentEl.appendChild(fSymbol.wrap);
  contentEl.appendChild(fMarket.wrap);
  contentEl.appendChild(msg);
  row.appendChild(btnCancel);
  row.appendChild(btnOk);
  contentEl.appendChild(row);

  // 填充现有数据
  if (strategy) {
    fName.input.value = strategy.name || '';
    fSymbol.input.value = strategy.symbol || '';
    fMarket.input.value = strategy.market_type || 'spot';
  }

  function close() {
    resetStrategyFormModalZ(modal);
    unlockStrategyParentModal(modal);
    modal.style.display = 'none';
  }

  btnCancel.addEventListener('click', close);
  modal.addEventListener('click', function(e) {
    if (e.target && e.target.getAttribute('data-close') === 'modal') close();
  });
  
  btnOk.addEventListener('click', async function() {
    msg.textContent = '提交中...';
    var name = fName.input.value.trim();
    var symbol = fSymbol.input.value.trim();
    var market = fMarket.input.value || 'spot';
    if (!name || !symbol) {
      msg.textContent = '请填写名称与符号';
      return;
    }
    try {
      if (strategy && strategy.id) {
        var response = await request('PUT', '/scripts/' + strategy.id, {
          name: name,
          symbol: symbol,
          market_type: market
        }, true);
        var result = await response.json();
        if (response.ok) {
          close();
          loadStrategyList();
          loadStrategyStats();
        } else {
          throw new Error(result.message || result.detail || '修改策略失败');
        }
      } else {
        var createdResp = await request('POST', '/scripts', {
          name: name,
          symbol: symbol,
          market_type: market
        }, true);
        var created = await createdResp.json();
        if (createdResp.ok) {
          // 若返回一次性口令，直接提示
          if (created && (created.webhook_url || created.url_token || created.body_secret)) {
            showReveal(contentEl, created);
          }
          close();
          loadStrategyList();
          loadStrategyStats();
        } else {
          throw new Error(created.message || created.detail || '创建策略失败');
        }
      }
    } catch (err) {
      msg.textContent = '失败：' + (err && err.message ? err.message : '未知错误');
    }
  });

  lockStrategyParentModal(modal);
  elevateStrategyFormModal(modal);
  modal.style.display = 'block';

  // 添加背景点击事件处理
  var backdrop = document.getElementById('strategy-form-backdrop');
  if (backdrop) {
    backdrop.onclick = function(e) {
      if (e.target === backdrop) {
        close();
      }
    };
  }
  
  // 防止内容区域点击事件冒泡
  var contentWrapper = document.getElementById('strategy-form-content-wrapper');
  if (contentWrapper) {
    contentWrapper.onclick = function(e) {
      e.stopPropagation();
    };
  }
  
  // 添加关闭按钮事件处理
  var closeBtn = document.getElementById('strategy-form-close-btn');
  if (closeBtn) {
    closeBtn.onclick = function() {
      close();
    };
  }
  
  console.log('Admin: 策略表单已打开');
}

// 关闭策略表单
window.closeStrategyForm = function() {
  var modal = document.getElementById('strategy-form-modal');
  if (modal) {
    resetStrategyFormModalZ(modal);
    unlockStrategyParentModal(modal);
    modal.style.display = 'none';
  }
};

// 保存策略
window.saveStrategy = async function(strategyId) {
  console.log('Admin: 保存策略:', strategyId);
  
  var nameInput = document.getElementById('strategy-name');
  var symbolInput = document.getElementById('strategy-symbol');
  var marketInput = document.getElementById('strategy-market');
  var msgEl = document.getElementById('strategy-form-msg');
  
  if (!nameInput || !symbolInput || !marketInput || !msgEl) return;
  
  var name = nameInput.value.trim();
  var symbol = symbolInput.value.trim();
  var market = marketInput.value || 'spot';
  
  if (!name || !symbol) {
    msgEl.textContent = '请填写策略名称和交易符号';
    return;
  }
  
  msgEl.textContent = '提交中...';
  
  try {
    var payload = {
      name: name,
      symbol: symbol,
      market_type: market
    };
    
    var response, apiPath, action;
    
    if (strategyId) {
      // 修改策略基础信息: PUT /scripts/{script_id}
      apiPath = '/scripts/' + strategyId;
      action = '修改';
      console.log('Admin: 调用修改策略API: PUT ' + apiPath);
      response = await request('PUT', apiPath, payload, true);
    } else {
      // 创建策略: POST /scripts
      apiPath = '/scripts';
      action = '创建';
      console.log('Admin: 调用创建策略API: POST ' + apiPath);
      response = await request('POST', apiPath, payload, true);
    }
    
    var result = await response.json();
    console.log('Admin: 策略' + action + 'API响应:', result);
    
    if (response.ok) {
      msgEl.textContent = action + '成功！';
      console.log('Admin: 策略' + action + '成功');
      
      closeStrategyForm();
      
      // 重新加载列表和统计
      loadStrategyList();
      loadStrategyStats();
      
      // 如果是创建新策略且有密钥信息，显示密钥
      if (!strategyId && result && (result.webhook_url || result.body_secret)) {
        setTimeout(function() {
          var message = '策略创建成功！请记录以下密钥信息：\n\n';
          if (result.webhook_url) {
            message += 'Webhook URL: ' + result.webhook_url + '\n';
          }
          if (result.body_secret) {
            message += 'Body Secret: ' + result.body_secret + '\n';
          }
          message += '\n请妥善保管这些信息，避免泄露！';
          alert(message);
        }, 500);
      }
    } else {
      throw new Error(result.message || result.detail || action + '策略失败');
    }
  } catch (err) {
    console.error('Admin: 保存策略失败:', err);
    msgEl.textContent = '保存失败: ' + err.message;
  }
};

// 构建策略筛选栏 - 与admin_strategy_manager.js保持一致
function buildStrategyFilterBar() {
  var filterBar = document.getElementById('strategy-filter-bar');
  if (!filterBar) return;
  
  filterBar.innerHTML = '';
  filterBar.style.display = 'flex';
  filterBar.style.gap = '8px';
  filterBar.style.margin = '8px 0';
  
  function inp(ph, key, type) {
    var i = document.createElement(type === 'select' ? 'select' : 'input');
    i.className = 'input';
    if (type !== 'select') i.placeholder = ph;
    if (type === 'select') {
      var o0 = document.createElement('option');
      o0.value = '';
      o0.textContent = ph;
      i.appendChild(o0);
    }
    i.addEventListener('change', change);
    i.addEventListener('input', change);
    i.setAttribute('data-key', key);
    return i;
  }
  
  function change() {
    var k = this.getAttribute('data-key');
    var v = (this.value || '').trim();
    strategyState[k] = v;
    strategyState.page = 1;
    loadStrategyList();
  }
  
  var nameI = inp('按名称', 'name');
  var symI = inp('按符号', 'symbol');
  var mktI = inp('市场类型', 'market_type', 'select');
  var o1 = document.createElement('option');
  o1.value = 'spot';
  o1.textContent = 'spot';
  var o2 = document.createElement('option');
  o2.value = 'perpetual';
  o2.textContent = 'perpetual';
  mktI.appendChild(o1);
  mktI.appendChild(o2);
  
  var stI = inp('状态', 'status', 'select');
  ['active', 'paused'].forEach(function(v) {
    var o = document.createElement('option');
    o.value = v;
    o.textContent = v;
    stI.appendChild(o);
  });
  
  var orderI = document.createElement('select');
  orderI.className = 'input';
  orderI.setAttribute('data-key', 'order');
  var od0 = document.createElement('option');
  od0.value = 'desc';
  od0.textContent = '创建时间：降序';
  var od1 = document.createElement('option');
  od1.value = 'asc';
  od1.textContent = '创建时间：升序';
  orderI.appendChild(od0);
  orderI.appendChild(od1);
  orderI.addEventListener('change', change);
  orderI.value = strategyState.order;
  
  filterBar.appendChild(nameI);
  filterBar.appendChild(symI);
  filterBar.appendChild(mktI);
  filterBar.appendChild(stI);
  filterBar.appendChild(orderI);
}

// 渲染策略分页 - 与admin_strategy_manager.js保持一致
function renderStrategyPager(data) {
  var pagerBar = document.getElementById('strategy-pager-bar');
  if (!pagerBar) {
    pagerBar = document.createElement('div');
    pagerBar.id = 'strategy-pager-bar';
    pagerBar.style.display = 'flex';
    pagerBar.style.justifyContent = 'space-between';
    pagerBar.style.alignItems = 'center';
    pagerBar.style.marginTop = '8px';
    // 将分页器添加到策略管理模态框
    var modal = document.getElementById('strategy-manager-modal');
    if (modal) {
      modal.appendChild(pagerBar);
    }
  }
  
  var total = data && (data.total || data.count);
  var page = data && (data.page || strategyState.page);
  var size = data && (data.page_size || strategyState.page_size);
  
  pagerBar.innerHTML = '';
  
  var info = document.createElement('span');
  info.className = 'muted small';
  info.textContent = total ? ('第 ' + page + ' 页 · 共 ' + total + ' 条') : ('第 ' + page + ' 页');
  
  var controls = document.createElement('div');
  controls.style.display = 'flex';
  controls.style.gap = '8px';
  
  var prev = document.createElement('button');
  prev.className = 'btn';
  prev.textContent = '上一页';
  prev.disabled = page <= 1;
  prev.addEventListener('click', function() {
    strategyState.page = Math.max(1, page - 1);
    loadStrategyList();
  });
  
  var next = document.createElement('button');
  next.className = 'btn';
  next.textContent = '下一页';
  var maxPage = total ? Math.ceil(total / size) : null;
  next.disabled = (maxPage && page >= maxPage);
  next.addEventListener('click', function() {
    strategyState.page = page + 1;
    if (maxPage) strategyState.page = Math.min(maxPage, strategyState.page);
    loadStrategyList();
  });
  
  controls.appendChild(prev);
  controls.appendChild(next);
  
  pagerBar.appendChild(info);
  pagerBar.appendChild(controls);
}

// 管理员概览功能
// 打开管理员概览
window.openAdminDashboard = function() {
  console.log('Admin: 打开管理员概览');
  var modal = document.getElementById('admin-dashboard-modal');
  if (modal) {
    modal.style.display = 'block';
    loadSystemOverview();
    loadSystemMonitoring();
    loadDataAnalysis();
  }
};

// 关闭管理员概览
window.closeAdminDashboard = function() {
  console.log('Admin: 关闭管理员概览');
  var modal = document.getElementById('admin-dashboard-modal');
  if (modal) {
    modal.style.display = 'none';
  }
};

// 加载系统概览
window.loadSystemOverview = async function() {
  console.log('Admin: 加载系统概览');
  
  var contentDiv = document.getElementById('system-overview-content');
  if (!contentDiv) return;
  
  try {
    contentDiv.innerHTML = '<div class="loading">加载中...</div>';
    
    // 模拟系统概览数据
    var overviewData = {
      totalUsers: 156,
      activeUsers: 142,
      totalConnectors: 8,
      systemStatus: '正常',
      totalStrategies: 12,
      activeStrategies: 10,
      totalSubscriptions: 45,
      activeSubscriptions: 38
    };
    
    var html = '<div class="risk-config-grid">';
    html += '<div class="config-item">';
    html += '<label>总用户数</label>';
    html += '<span class="config-value">' + overviewData.totalUsers + '</span>';
    html += '</div>';
    html += '<div class="config-item">';
    html += '<label>活跃用户</label>';
    html += '<span class="config-value">' + overviewData.activeUsers + '</span>';
    html += '</div>';
    html += '<div class="config-item">';
    html += '<label>连接器总数</label>';
    html += '<span class="config-value">' + overviewData.totalConnectors + '</span>';
    html += '</div>';
    html += '<div class="config-item">';
    html += '<label>系统状态</label>';
    html += '<span class="config-value success">' + overviewData.systemStatus + '</span>';
    html += '</div>';
    html += '<div class="config-item">';
    html += '<label>总策略数</label>';
    html += '<span class="config-value">' + overviewData.totalStrategies + '</span>';
    html += '</div>';
    html += '<div class="config-item">';
    html += '<label>活跃策略</label>';
    html += '<span class="config-value">' + overviewData.activeStrategies + '</span>';
    html += '</div>';
    html += '<div class="config-item">';
    html += '<label>总订阅数</label>';
    html += '<span class="config-value">' + overviewData.totalSubscriptions + '</span>';
    html += '</div>';
    html += '<div class="config-item">';
    html += '<label>活跃订阅</label>';
    html += '<span class="config-value">' + overviewData.activeSubscriptions + '</span>';
    html += '</div>';
    html += '</div>';
    
    contentDiv.innerHTML = html;
  } catch (err) {
    console.error('Admin: 加载系统概览失败:', err);
    contentDiv.innerHTML = '<p class="muted">加载失败: ' + err.message + '</p>';
  }
};

// 刷新系统统计
window.refreshSystemStats = function() {
  console.log('Admin: 刷新系统统计');
  loadSystemOverview();
};

// 加载系统监控
window.loadSystemMonitoring = async function() {
  console.log('Admin: 加载系统监控');
  
  var contentDiv = document.getElementById('system-monitoring-content');
  if (!contentDiv) return;
  
  try {
    contentDiv.innerHTML = '<div class="loading">加载中...</div>';
    
    // 模拟系统监控数据
    var monitoringData = {
      cpuUsage: '45%',
      memoryUsage: '62%',
      diskUsage: '38%',
      networkStatus: '正常',
      apiResponseTime: '120ms',
      activeConnections: 156,
      errorRate: '0.2%',
      uptime: '99.9%'
    };
    
    var html = '<div class="risk-config-grid">';
    html += '<div class="config-item">';
    html += '<label>CPU使用率</label>';
    html += '<span class="config-value">' + monitoringData.cpuUsage + '</span>';
    html += '</div>';
    html += '<div class="config-item">';
    html += '<label>内存使用率</label>';
    html += '<span class="config-value">' + monitoringData.memoryUsage + '</span>';
    html += '</div>';
    html += '<div class="config-item">';
    html += '<label>磁盘使用率</label>';
    html += '<span class="config-value">' + monitoringData.diskUsage + '</span>';
    html += '</div>';
    html += '<div class="config-item">';
    html += '<label>网络状态</label>';
    html += '<span class="config-value success">' + monitoringData.networkStatus + '</span>';
    html += '</div>';
    html += '<div class="config-item">';
    html += '<label>API响应时间</label>';
    html += '<span class="config-value">' + monitoringData.apiResponseTime + '</span>';
    html += '</div>';
    html += '<div class="config-item">';
    html += '<label>活跃连接数</label>';
    html += '<span class="config-value">' + monitoringData.activeConnections + '</span>';
    html += '</div>';
    html += '<div class="config-item">';
    html += '<label>错误率</label>';
    html += '<span class="config-value">' + monitoringData.errorRate + '</span>';
    html += '</div>';
    html += '<div class="config-item">';
    html += '<label>系统运行时间</label>';
    html += '<span class="config-value success">' + monitoringData.uptime + '</span>';
    html += '</div>';
    html += '</div>';
    
    contentDiv.innerHTML = html;
  } catch (err) {
    console.error('Admin: 加载系统监控失败:', err);
    contentDiv.innerHTML = '<p class="muted">加载失败: ' + err.message + '</p>';
  }
};

// 刷新系统监控
window.refreshSystemMonitoring = function() {
  console.log('Admin: 刷新系统监控');
  loadSystemMonitoring();
};

// 加载数据分析
window.loadDataAnalysis = async function() {
  console.log('Admin: 加载数据分析');
  
  var contentDiv = document.getElementById('data-analysis-content');
  if (!contentDiv) return;
  
  try {
    contentDiv.innerHTML = '<div class="loading">加载中...</div>';
    
    // 模拟数据分析
    var analysisData = {
      totalVolume: '$2,456,789',
      dailyVolume: '$156,789',
      totalTrades: 12456,
      successRate: '94.2%',
      avgOrderSize: '$198.45',
      topSymbol: 'BTC-USDT',
      userGrowth: '+12.5%',
      revenue: '$45,678'
    };
    
    var html = '<div class="risk-config-grid">';
    html += '<div class="config-item">';
    html += '<label>总交易量</label>';
    html += '<span class="config-value">' + analysisData.totalVolume + '</span>';
    html += '</div>';
    html += '<div class="config-item">';
    html += '<label>日交易量</label>';
    html += '<span class="config-value">' + analysisData.dailyVolume + '</span>';
    html += '</div>';
    html += '<div class="config-item">';
    html += '<label>总交易数</label>';
    html += '<span class="config-value">' + analysisData.totalTrades + '</span>';
    html += '</div>';
    html += '<div class="config-item">';
    html += '<label>成功率</label>';
    html += '<span class="config-value success">' + analysisData.successRate + '</span>';
    html += '</div>';
    html += '<div class="config-item">';
    html += '<label>平均订单大小</label>';
    html += '<span class="config-value">' + analysisData.avgOrderSize + '</span>';
    html += '</div>';
    html += '<div class="config-item">';
    html += '<label>热门交易对</label>';
    html += '<span class="config-value">' + analysisData.topSymbol + '</span>';
    html += '</div>';
    html += '<div class="config-item">';
    html += '<label>用户增长</label>';
    html += '<span class="config-value success">' + analysisData.userGrowth + '</span>';
    html += '</div>';
    html += '<div class="config-item">';
    html += '<label>收入</label>';
    html += '<span class="config-value">' + analysisData.revenue + '</span>';
    html += '</div>';
    html += '</div>';
    
    contentDiv.innerHTML = html;
  } catch (err) {
    console.error('Admin: 加载数据分析失败:', err);
    contentDiv.innerHTML = '<p class="muted">加载失败: ' + err.message + '</p>';
  }
};

// 刷新数据分析
window.refreshDataAnalysis = function() {
  console.log('Admin: 刷新数据分析');
  loadDataAnalysis();
};

// 用户管理功能
window.openUserManagement = function() {
  console.log('Admin: 打开用户管理');
  // 这里可以实现用户管理功能
  alert('用户管理功能正在开发中...');
};

// 策略管理页面专用函数
// 加载策略统计（用于策略管理页面）
window.loadStrategyStats = async function() {
  console.log('Admin: 加载策略统计');
  
  try {
    // 调用策略列表API获取统计数据
    var response = await request('GET', '/scripts', null, true);
    var data = await response.json();
    
    if (response.ok) {
      var items = Array.isArray(data) ? data : (data.items || []);
      
      // 计算统计数据
      var totalStrategies = items.length;
      var activeStrategies = items.filter(function(script) { 
        return script.status === 'active' || script.enabled; 
      }).length;
      var pausedStrategies = totalStrategies - activeStrategies;
      var uniqueSymbols = new Set(items.map(function(script) { 
        return script.symbol; 
      })).size;
      
      // 更新页面显示
      var totalEl = document.getElementById('total-strategies');
      var activeEl = document.getElementById('active-strategies');
      var pausedEl = document.getElementById('paused-strategies');
      var symbolsEl = document.getElementById('total-symbols');
      
      if (totalEl) totalEl.textContent = totalStrategies;
      if (activeEl) activeEl.textContent = activeStrategies;
      if (pausedEl) pausedEl.textContent = pausedStrategies;
      if (symbolsEl) symbolsEl.textContent = uniqueSymbols;
      
    } else {
      throw new Error(data.message || data.detail || '获取策略统计失败');
    }
  } catch (err) {
    console.error('Admin: 加载策略统计失败:', err);
    
    // 使用模拟数据
    var totalEl = document.getElementById('total-strategies');
    var activeEl = document.getElementById('active-strategies');
    var pausedEl = document.getElementById('paused-strategies');
    var symbolsEl = document.getElementById('total-symbols');
    
    if (totalEl) totalEl.textContent = '8';
    if (activeEl) activeEl.textContent = '6';
    if (pausedEl) pausedEl.textContent = '2';
    if (symbolsEl) symbolsEl.textContent = '5';
  }
};

// 加载策略列表（用于策略管理页面）
window.loadStrategyList = async function() {
  console.log('Admin: 加载策略列表');
  
  var listDiv = document.getElementById('strategy-list-content');
  if (!listDiv) return;
  
  try {
    listDiv.innerHTML = '<div class="loading">加载中...</div>';
    
    // 构建查询参数
    var q = [];
    if (strategyState.page) q.push('page=' + encodeURIComponent(strategyState.page));
    if (strategyState.page_size) q.push('page_size=' + encodeURIComponent(strategyState.page_size));
    if (strategyState.name) q.push('name=' + encodeURIComponent(strategyState.name));
    if (strategyState.symbol) q.push('symbol=' + encodeURIComponent(strategyState.symbol));
    if (strategyState.market_type) q.push('market_type=' + encodeURIComponent(strategyState.market_type));
    if (strategyState.status) q.push('status=' + encodeURIComponent(strategyState.status));
    if (strategyState.order) q.push('order=' + encodeURIComponent(strategyState.order));
    
    var path = '/scripts' + (q.length ? ('?' + q.join('&')) : '');
    
    var response = await request('GET', path, null, true);
    var data = await response.json();
    
    if (response.ok) {
      var items = Array.isArray(data) ? data : (data.items || []);
      renderStrategyListForPage(items);
      renderStrategyPagerForPage(data);
    } else {
      throw new Error(data.message || data.detail || '获取策略列表失败');
    }
  } catch (err) {
    console.error('Admin: 加载策略列表失败:', err);
    
    // 使用模拟数据
    var mockStrategies = [
      {
        id: 1,
        name: '趋势跟随策略',
        symbol: 'BTC-USDT',
        market_type: 'spot',
        status: 'active',
        enabled: true,
        created_at: new Date(Date.now() - 86400000).toISOString()
      },
      {
        id: 2,
        name: '均值回归策略',
        symbol: 'ETH-USDT',
        market_type: 'perpetual',
        status: 'paused',
        enabled: false,
        created_at: new Date(Date.now() - 172800000).toISOString()
      },
      {
        id: 3,
        name: '动量突破策略',
        symbol: 'BNB-USDT',
        market_type: 'spot',
        status: 'active',
        enabled: true,
        created_at: new Date(Date.now() - 259200000).toISOString()
      }
    ];
    
    renderStrategyListForPage(mockStrategies);
  }
};

// 渲染策略列表（用于策略管理页面）
function renderStrategyListForPage(strategies) {
  var listDiv = document.getElementById('strategy-list-content');
  if (!listDiv) return;
  
  listDiv.innerHTML = '';
  if (!strategies || strategies.length === 0) {
    listDiv.innerHTML = '<div class="loading">暂无策略</div>';
    return;
  }
  
  strategies.forEach(function(strategy) {
    var statusClass = (strategy.status === 'active' || strategy.enabled) ? 'status-active' : 'status-paused';
    var statusText = (strategy.status === 'active' || strategy.enabled) ? '启用' : '停用';
    var marketText = strategy.market_type === 'spot' ? '现货' : '合约';
    var createdTime = new Date(strategy.created_at).toLocaleString('zh-CN');
    
    var strategyItem = document.createElement('div');
    strategyItem.className = 'strategy-item';
    
    var header = document.createElement('div');
    header.className = 'strategy-header';
    
    var title = document.createElement('div');
    title.className = 'strategy-title';
    title.textContent = (strategy.name || '未命名') + ' · ' + (strategy.symbol || '');
    
    var status = document.createElement('div');
    status.className = 'strategy-status ' + statusClass;
    status.textContent = statusText;
    
    header.appendChild(title);
    header.appendChild(status);
    
    var details = document.createElement('div');
    details.className = 'strategy-details';
    details.innerHTML = '<div>市场: ' + marketText + '</div><div>创建: ' + createdTime + '</div>';
    
    var actions = document.createElement('div');
    actions.className = 'strategy-actions';
    
    var editBtn = document.createElement('button');
    editBtn.className = 'btn btn-secondary';
    editBtn.textContent = '修改';
    editBtn.onclick = function() {
      editStrategy(strategy.id);
    };
    
    var deleteBtn = document.createElement('button');
    deleteBtn.className = 'btn btn-danger';
    deleteBtn.textContent = '删除';
    deleteBtn.onclick = function() {
      deleteStrategy(strategy.id);
    };
    
    var revealBtn = document.createElement('button');
    revealBtn.className = 'btn btn-success';
    revealBtn.textContent = '查看密钥';
    revealBtn.onclick = function() {
      revealStrategySecret(strategy.id);
    };
    
    var toggleBtn = document.createElement('button');
    toggleBtn.className = 'btn ' + (strategy.status === 'active' ? 'btn-danger' : 'btn-success');
    toggleBtn.id = 'status-action-' + strategy.id;
    toggleBtn.textContent = strategy.status === 'active' ? '暂停' : '启用';
    toggleBtn.onclick = async function() {
      var action = strategy.status === 'active' ? 'pause' : 'resume';
      toggleBtn.disabled = true;
      try {
        await toggleStrategyStatus(strategy.id, action);
        strategy.status = action === 'pause' ? 'paused' : 'active';
        toggleBtn.className = 'btn ' + (strategy.status === 'active' ? 'btn-danger' : 'btn-success');
        toggleBtn.textContent = strategy.status === 'active' ? '暂停' : '启用';
      } finally {
        toggleBtn.disabled = false;
      }
    };
    
    actions.appendChild(editBtn);
    actions.appendChild(deleteBtn);
    actions.appendChild(revealBtn);
    actions.appendChild(toggleBtn);
    
    strategyItem.appendChild(header);
    strategyItem.appendChild(details);
    strategyItem.appendChild(actions);
    
    listDiv.appendChild(strategyItem);
  });
}

// 渲染策略分页（用于策略管理页面）
function renderStrategyPagerForPage(data) {
  var pagerBar = document.getElementById('strategy-pager-bar');
  if (!pagerBar) return;
  
  var total = data && (data.total || data.count);
  var page = data && (data.page || strategyState.page);
  var size = data && (data.page_size || strategyState.page_size);
  
  pagerBar.innerHTML = '';
  
  var info = document.createElement('span');
  info.className = 'pager-info';
  info.textContent = total ? ('第 ' + page + ' 页 · 共 ' + total + ' 条') : ('第 ' + page + ' 页');
  
  var controls = document.createElement('div');
  controls.className = 'pager-controls';
  
  var prev = document.createElement('button');
  prev.className = 'btn btn-secondary';
  prev.textContent = '上一页';
  prev.disabled = page <= 1;
  prev.onclick = function() {
    strategyState.page = Math.max(1, page - 1);
    loadStrategyList();
  };
  
  var next = document.createElement('button');
  next.className = 'btn btn-secondary';
  next.textContent = '下一页';
  var maxPage = total ? Math.ceil(total / size) : null;
  next.disabled = (maxPage && page >= maxPage);
  next.onclick = function() {
    strategyState.page = page + 1;
    if (maxPage) strategyState.page = Math.min(maxPage, strategyState.page);
    loadStrategyList();
  };
  
  controls.appendChild(prev);
  controls.appendChild(next);
  
  pagerBar.appendChild(info);
  pagerBar.appendChild(controls);
}

// 订阅管理功能
// 打开订阅管理
window.openSubscriptionManager = function() {
  console.log('Admin: 打开订阅管理');
  var modal = document.getElementById('subscription-manager-modal');
  if (modal) {
    modal.style.display = 'block';
    loadSubscriptionStats();
    loadAllSubscriptions();
  }
};

// 关闭订阅管理
window.closeSubscriptionManager = function() {
  console.log('Admin: 关闭订阅管理');
  var modal = document.getElementById('subscription-manager-modal');
  if (modal) {
    modal.style.display = 'none';
  }
};

// 加载订阅统计
window.loadSubscriptionStats = async function() {
  console.log('Admin: 加载订阅统计');
  
  var statsDiv = document.getElementById('subscription-stats-content');
  if (!statsDiv) return;
  
  try {
    statsDiv.innerHTML = '<div class="loading">加载中...</div>';
    
    // 调用管理员订阅API获取统计数据: GET /subscriptions/admin/all
    console.log('Admin: 调用订阅统计API: GET /subscriptions/admin/all');
    var response = await request('GET', '/subscriptions/admin/all', null, true);
    var subscriptionsData = await response.json();
    
    console.log('Admin: 订阅统计API响应:', subscriptionsData);
    
    if (response.ok && subscriptionsData) {
      renderSubscriptionStats(subscriptionsData);
    } else {
      throw new Error(subscriptionsData.message || subscriptionsData.detail || '获取订阅统计失败');
    }
  } catch (err) {
    console.error('Admin: 加载订阅统计失败:', err);
    
    // 显示错误信息
    statsDiv.innerHTML = '<p class="muted">统计加载失败: ' + err.message + '</p>';
    
    // 如果API失败，提供模拟数据用于演示
    console.log('Admin: 使用模拟订阅统计数据');
    var mockStats = {
      totalSubscriptions: 45,
      activeSubscriptions: 38,
      pausedSubscriptions: 7,
      totalUsers: 12,
      totalStrategies: 8
    };
    
    renderSubscriptionStats(mockStats);
  }
};

// 渲染订阅统计
window.renderSubscriptionStats = function(data) {
  var statsDiv = document.getElementById('subscription-stats-content');
  if (!statsDiv) return;
  
  var stats = {};
  
  if (Array.isArray(data)) {
    // 从订阅数据计算统计
    var totalSubscriptions = data.length;
    var activeSubscriptions = data.filter(function(sub) { 
      return sub.status === 'active'; 
    }).length;
    var pausedSubscriptions = totalSubscriptions - activeSubscriptions;
    var uniqueUsers = new Set(data.map(function(sub) { 
      return sub.user_id; 
    })).size;
    var uniqueStrategies = new Set(data.map(function(sub) { 
      return sub.script_id; 
    })).size;
    
    stats = {
      totalSubscriptions: totalSubscriptions,
      activeSubscriptions: activeSubscriptions,
      pausedSubscriptions: pausedSubscriptions,
      totalUsers: uniqueUsers,
      totalStrategies: uniqueStrategies
    };
  } else {
    // 直接使用传入的统计数据
    stats = data;
  }
  
  var html = '<div class="risk-config-grid">';
  html += '<div class="config-item">';
  html += '<label>总订阅数</label>';
  html += '<span class="config-value">' + (stats.totalSubscriptions || 0) + '</span>';
  html += '</div>';
  html += '<div class="config-item">';
  html += '<label>活跃订阅</label>';
  html += '<span class="config-value">' + (stats.activeSubscriptions || 0) + '</span>';
  html += '</div>';
  html += '<div class="config-item">';
  html += '<label>暂停订阅</label>';
  html += '<span class="config-value">' + (stats.pausedSubscriptions || 0) + '</span>';
  html += '</div>';
  html += '<div class="config-item">';
  html += '<label>订阅用户数</label>';
  html += '<span class="config-value">' + (stats.totalUsers || 0) + '</span>';
  html += '</div>';
  html += '<div class="config-item">';
  html += '<label>策略数量</label>';
  html += '<span class="config-value">' + (stats.totalStrategies || 0) + '</span>';
  html += '</div>';
  html += '<div class="config-item">';
  html += '<label>活跃率</label>';
  html += '<span class="config-value">' + (stats.totalSubscriptions > 0 ? Math.round((stats.activeSubscriptions / stats.totalSubscriptions) * 100) : 0) + '%</span>';
  html += '</div>';
  html += '</div>';
  
  statsDiv.innerHTML = html;
};

// 加载所有订阅
window.loadAllSubscriptions = async function() {
  console.log('Admin: 加载所有订阅');
  
  var listDiv = document.getElementById('admin-subscriptions-list');
  if (!listDiv) return;
  
  try {
    listDiv.innerHTML = '<div class="loading">加载中...</div>';
    
    // 调用管理员订阅API: GET /subscriptions/admin/all
    console.log('Admin: 调用订阅列表API: GET /subscriptions/admin/all');
    var response = await request('GET', '/subscriptions/admin/all', null, true);
    var subscriptionsData = await response.json();
    
    console.log('Admin: 订阅列表API响应:', subscriptionsData);
    
    if (response.ok && subscriptionsData) {
      var items = Array.isArray(subscriptionsData) ? subscriptionsData : (subscriptionsData.items || subscriptionsData.data || []);
      
      if (items && items.length > 0) {
        renderAllSubscriptions(items);
      } else {
        listDiv.innerHTML = '<p class="muted">暂无订阅记录</p>';
      }
    } else {
      throw new Error(subscriptionsData.message || subscriptionsData.detail || '获取订阅列表失败');
    }
  } catch (err) {
    console.error('Admin: 加载订阅列表失败:', err);
    
    // 显示错误信息
    listDiv.innerHTML = '<p class="muted">加载失败: ' + err.message + '</p>';
    
    // 如果API失败，提供模拟数据用于演示
    console.log('Admin: 使用模拟订阅数据');
    var mockSubscriptions = [
      {
        id: 1,
        user_id: 'user1',
        user_email: 'user1@example.com',
        script_id: 1,
        script_name: '趋势跟随策略',
        connector_name: 'gate_io',
        account_name: 'user1@example.com',
        status: 'active',
        allocation: { mode: 'percent_of_equity', value: 10 },
        market_type: 'spot',
        max_notional: 1000,
        slippage_bps: 10,
        created_at: new Date(Date.now() - 86400000).toISOString()
      },
      {
        id: 2,
        user_id: 'user2',
        user_email: 'user2@example.com',
        script_id: 2,
        script_name: '均值回归策略',
        connector_name: 'gate_io',
        account_name: 'user2@example.com',
        status: 'paused',
        allocation: { mode: 'percent_of_equity', value: 15 },
        market_type: 'perpetual',
        max_notional: 2000,
        slippage_bps: 5,
        created_at: new Date(Date.now() - 172800000).toISOString()
      }
    ];
    
    renderAllSubscriptions(mockSubscriptions);
  }
};

// 渲染所有订阅
window.renderAllSubscriptions = function(subscriptions) {
  var listDiv = document.getElementById('admin-subscriptions-list');
  if (!listDiv) return;
  
  if (!subscriptions || subscriptions.length === 0) {
    listDiv.innerHTML = '<p class="muted">暂无订阅记录</p>';
    return;
  }
  
  var html = '';
  subscriptions.forEach(function(sub) {
    var statusClass = sub.status === 'active' ? 'success' : 'warning';
    var statusText = sub.status === 'active' ? '活跃' : '暂停';
    var marketText = sub.market_type === 'spot' ? '现货' : '合约';
    var createdTime = new Date(sub.created_at).toLocaleString('zh-CN');
    
    html += '<div class="strategy-item">';
    html += '<div class="strategy-header">';
    html += '<div class="strategy-title">' + (sub.script_name || '策略 #' + sub.script_id) + ' · ' + (sub.user_email || sub.user_id) + '</div>';
    html += '<div class="strategy-status ' + statusClass + '">' + statusText + '</div>';
    html += '</div>';
    html += '<div class="strategy-body">';
    html += '<div class="strategy-field">';
    html += '<label>用户</label>';
    html += '<input type="text" value="' + (sub.user_email || sub.user_id) + '" readonly>';
    html += '</div>';
    html += '<div class="strategy-field">';
    html += '<label>连接器</label>';
    html += '<input type="text" value="' + (sub.connector_name || '-') + '" readonly>';
    html += '</div>';
    html += '<div class="strategy-field">';
    html += '<label>市场</label>';
    html += '<input type="text" value="' + marketText + '" readonly>';
    html += '</div>';
    html += '<div class="strategy-field">';
    html += '<label>投入比例</label>';
    html += '<input type="text" value="' + (sub.allocation ? sub.allocation.value + '%' : '-') + '" readonly>';
    html += '</div>';
    html += '<div class="strategy-field">';
    html += '<label>单笔上限</label>';
    html += '<input type="text" value="' + (sub.max_notional || '-') + '" readonly>';
    html += '</div>';
    html += '<div class="strategy-field">';
    html += '<label>滑点</label>';
    html += '<input type="text" value="' + (sub.slippage_bps || '-') + ' bps" readonly>';
    html += '</div>';
    html += '<div class="strategy-field">';
    html += '<label>创建时间</label>';
    html += '<input type="text" value="' + createdTime + '" readonly>';
    html += '</div>';
    
    html += '<div class="strategy-actions">';
    html += '<button class="btn" onclick="editSubscription(' + sub.id + ')">编辑</button>';
    html += '<button class="btn ' + (sub.status === 'active' ? 'warning' : 'success') + '" onclick="toggleSubscriptionStatus(' + sub.id + ', \'' + sub.status + '\')">' + (sub.status === 'active' ? '暂停' : '启用') + '</button>';
    html += '<button class="btn danger" onclick="deleteSubscription(' + sub.id + ')">删除</button>';
    html += '</div>';
    html += '</div>';
    html += '</div>';
  });
  
  listDiv.innerHTML = html;
};
